wait until all threads finish their work in java wait until all threads finish their work in java multithreading multithreading

wait until all threads finish their work in java


The approach I take is to use an ExecutorService to manage pools of threads.

ExecutorService es = Executors.newCachedThreadPool();for(int i=0;i<5;i++)    es.execute(new Runnable() { /*  your task */ });es.shutdown();boolean finished = es.awaitTermination(1, TimeUnit.MINUTES);// all tasks have finished or the time has been reached.


You can join to the threads. The join blocks until the thread completes.

for (Thread thread : threads) {    thread.join();}

Note that join throws an InterruptedException. You'll have to decide what to do if that happens (e.g. try to cancel the other threads to prevent unnecessary work being done).


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()

    Executes the given tasks, returning a list of Futures holding their status and results when everything is completed.

    Refer to this related SE question for code example:

    How to use invokeAll() to let all thread pool do their task?

  3. CountDownLatch

    A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

    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.

    Refer to this question for usage of CountDownLatch

    How to wait for a thread that spawns it's own thread?

  4. ForkJoinPool or newWorkStealingPool() in Executors

  5. Iterate through all Future objects created after submitting to ExecutorService