wait until all threads finish their work in java

后端 未结 16 2235
情深已故
情深已故 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: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?

提交回复
热议问题