Skip to content
Advertisement

How to wait for a number 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());
            t.start();
        }
        // wait for all threads' run() methods to complete before continuing
    }

    public void run() {
        // do something here
    }


}

How do I alter this so the main() method pauses at the comment until all threads’ run() methods exit? Thanks!

Advertisement

Answer

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

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

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.

Advertisement