How to wait for a number of threads to complete? How to wait for a number of threads to complete? multithreading multithreading

How to wait for a number of threads to complete?


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.


One way would be to make a List of Threads, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call join() on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.

A better approach is to use an ExecutorService and its associated methods:

List<Callable> callables = ... // assemble list of Callables here                               // Like Runnable but can return a valueExecutorService execSvc = Executors.newCachedThreadPool();List<Future<?>> results = execSvc.invokeAll(callables);// Note: You may not care about the return values, in which case don't//       bother saving them

Using an ExecutorService (and all of the new stuff from Java 5's concurrency utilities) is incredibly flexible, and the above example barely even scratches the surface.


import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class DoSomethingInAThread implements Runnable{   public static void main(String[] args) throws ExecutionException, InterruptedException   {      //limit the number of actual threads      int poolSize = 10;      ExecutorService service = Executors.newFixedThreadPool(poolSize);      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();      for (int n = 0; n < 1000; n++)      {         Future f = service.submit(new DoSomethingInAThread());         futures.add(f);      }      // wait for all tasks to complete before continuing      for (Future<Runnable> f : futures)      {         f.get();      }      //shut down the executor service so that this thread can exit      service.shutdownNow();   }   public void run()   {      // do something here   }}