by BehindJava

How to wait for a number of threads to complete in Java

Home » java » How to wait for a number of threads to complete in Java

In this tutorial we are going to learn about waiting for a number of threads to complete in Java.

Have a look at various solutions.

  1. join() API has been introduced in early versions of Java. Some good alternatives are available with this concurrent package since the JDK 1.5 release.
  2. ExecutorService#invokeAll()
  3. Executes the given tasks, returning a list of Futures holding their status and results when everything is completed.
  4. CountDownLatch
  5. A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
  6. A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon — the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
  7. ForkJoinPool or newWorkStealingPool() in Executors
  8. Iterate through all Future objects created after submitting to ExecutorService

Instead of join(), which is an old API, you can use CountDownLatch. I have modified your code as below to fulfil your requirement.

import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable{
    CountDownLatch latch;
    public DoSomethingInAThread(CountDownLatch latch){
        this.latch = latch;
    } 
    public void run() {
        try{
            System.out.println("Do some thing");
            latch.countDown();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

public class CountDownLatchDemo {
    public static void main(String[] args) {
        try{
            CountDownLatch latch = new CountDownLatch(1000);
            for (int n=0; n<1000; n++) {
                Thread t = new Thread(new DoSomethingInAThread(latch));
                t.start();
            }
            latch.await();
            System.out.println("In Main thread after completion of 1000 threads");
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Output:

In Main thread after completion of 1000 threads

Explanation:

  1. CountDownLatch has been initialized with given count 1000 as per your requirement.
  2. Each worker thread DoSomethingInAThread will decrement the CountDownLatch, which has been passed in constructor.
  3. Main thread CountDownLatchDemo await() till the count has become zero. Once the count has become zero, you will get below line in output.