How to wait until all threads finish their work in java

One way is to use an ExecutorService to manage pools of threads.
1
 2
 3
 4
 5
 6
 7
 8
 9
10
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<8;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();

//wait till this executor terminated,
//loop if the timeout elapsed before termination
while(!es.awaitTermination(1, TimeUnit.MINUTES)) {
//Now begin your following job
}

One more example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 WaitForThreadExample 
{
   public static void main(String[] args) throws ExecutionException, InterruptedException
   {
      //limit the number of actual threads
      int poolSize = 8;
      ExecutorService service = Executors.newFixedThreadPool(poolSize);
      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();

      for (int n = 0; n < 888; n++)
      {
         Future f = service.submit(new YourRunnableClass());
         futures.add(f);
      }

      // wait for all tasks to complete before continuing
      for (Future<Runnable> f : futures)
      {
         f.get();
      //saveIt=f.get if you want to save the result
      }

      //shut down the executor service so that this thread can exit
      service.shutdownNow();
      //you can wait in a loop like former example
   }
}

Another way to save the values return by the threads:

1
2
3
4
5
List<Callable> callables = ... 
// assemble list of Callables here
// Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll();

Another way is to 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.

Comments

Popular posts from this blog

How to get Active Transactions and Locks from MySQL

Example of a PAC file