wait until all threads finish their work in java

后端 未结 16 1923
情深已故
情深已故 2020-11-22 14:10

I\'m writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer

相关标签:
16条回答
  • 2020-11-22 14:41

    You can use Threadf#join method for this purpose.

    0 讨论(0)
  • 2020-11-22 14:41

    An executor service can be used to manage multiple threads including status and completion. See http://programmingexamples.wikidot.com/executorservice

    0 讨论(0)
  • 2020-11-22 14:46

    try this, will work.

      Thread[] threads = new Thread[10];
    
      List<Thread> allThreads = new ArrayList<Thread>();
    
      for(Thread thread : threads){
    
            if(null != thread){
    
                  if(thread.isAlive()){
    
                        allThreads.add(thread);
    
                  }
    
            }
    
      }
    
      while(!allThreads.isEmpty()){
    
            Iterator<Thread> ite = allThreads.iterator();
    
            while(ite.hasNext()){
    
                  Thread thread = ite.next();
    
                  if(!thread.isAlive()){
    
                       ite.remove();
                  }
    
            }
    
       }
    
    0 讨论(0)
  • 2020-11-22 14:48

    Wait/block the Thread Main until some other threads complete their work.

    As @Ravindra babu said it can be achieved in various ways, but showing with examples.

    • java.lang.Thread.join() Since:1.0

      public static void joiningThreads() throws InterruptedException {
          Thread t1 = new Thread( new LatchTask(1, null), "T1" );
          Thread t2 = new Thread( new LatchTask(7, null), "T2" );
          Thread t3 = new Thread( new LatchTask(5, null), "T3" );
          Thread t4 = new Thread( new LatchTask(2, null), "T4" );
      
          // Start all the threads
          t1.start();
          t2.start();
          t3.start();
          t4.start();
      
          // Wait till all threads completes
          t1.join();
          t2.join();
          t3.join();
          t4.join();
      }
      
    • java.util.concurrent.CountDownLatch Since:1.5

      • .countDown() « Decrements the count of the latch group.
      • .await() « The await methods block until the current count reaches zero.

      If you created latchGroupCount = 4 then countDown() should be called 4 times to make count 0. So, that await() will release the blocking threads.

      public static void latchThreads() throws InterruptedException {
          int latchGroupCount = 4;
          CountDownLatch latch = new CountDownLatch(latchGroupCount);
          Thread t1 = new Thread( new LatchTask(1, latch), "T1" );
          Thread t2 = new Thread( new LatchTask(7, latch), "T2" );
          Thread t3 = new Thread( new LatchTask(5, latch), "T3" );
          Thread t4 = new Thread( new LatchTask(2, latch), "T4" );
      
          t1.start();
          t2.start();
          t3.start();
          t4.start();
      
          //latch.countDown();
      
          latch.await(); // block until latchGroupCount is 0.
      }
      

    Example code of Threaded class LatchTask. To test the approach use joiningThreads(); and latchThreads(); from main method.

    class LatchTask extends Thread {
        CountDownLatch latch;
        int iterations = 10;
        public LatchTask(int iterations, CountDownLatch latch) {
            this.iterations = iterations;
            this.latch = latch;
        }
    
        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " : Started Task...");
    
            for (int i = 0; i < iterations; i++) {
                System.out.println(threadName + " : " + i);
                MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
            }
            System.out.println(threadName + " : Completed Task");
            // countDown() « Decrements the count of the latch group.
            if(latch != null)
                latch.countDown();
        }
    }
    
    • CyclicBarriers A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
      CyclicBarrier barrier = new CyclicBarrier(3);
      barrier.await();
      
      For example refer this Concurrent_ParallelNotifyies class.

    • Executer framework: we can use ExecutorService to create a thread pool, and tracks the progress of the asynchronous tasks with Future.

      • submit(Runnable), submit(Callable) which return Future Object. By using future.get() function we can block the main thread till the working threads completes its work.

      • invokeAll(...) - returns a list of Future objects via which you can obtain the results of the executions of each Callable.

    Find example of using Interfaces Runnable, Callable with Executor framework.


    @See also

    • Find out thread is still alive?
    0 讨论(0)
  • 2020-11-22 14:48

    You do

    for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
        t.join()
    

    After this for loop, you can be sure all threads have finished their jobs.

    0 讨论(0)
  • 2020-11-22 14:50

    Another possibility is the CountDownLatch object, which is useful for simple situations : since you know in advance the number of threads, you initialize it with the relevant count, and pass the reference of the object to each thread.
    Upon completion of its task, each thread calls CountDownLatch.countDown() which decrements the internal counter. The main thread, after starting all others, should do the CountDownLatch.await() blocking call. It will be released as soon as the internal counter has reached 0.

    Pay attention that with this object, an InterruptedException can be thrown as well.

    0 讨论(0)
提交回复
热议问题