DivideByHero DivideByHero - 1 year ago 78
Java Question

How to wait for a set of threads to complete?

What is a way to simply wait for all threaded process to finish? For example, let's say I have:

public class DoSomethingInAThread implements Runnable{

public static void main(String[] args) {
for (int n=0; n<1000; n++) {
Thread t = new Thread(new DoSomethingInAThread());
// wait for all threads' run() methods to complete before continuing

public void run() {
// do something here


How do I alter this so the
method pauses at the comment until all threads'
methods exit? Thanks!

Answer Source

You put all threads in an array, start them all, and then have a loop

for(i = 0; i < threads.length; i++)

Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that's not a problem: when the loop exits, all threads are completed.