Possible Duplicates:
ExecutorService, how to wait for all tasks to finish
Java ExecutorService: awaitTermination of all recursively created tasks
Is there a way to block the current thread until an ExecutorService
has finished all its tasks?
executor.execute(task1);
executor.execute(task2);
executor.execute(task3);
executor.execute(task4);
executor.execute(task5);
// ...now I want to block until all tasks have finished executing...
System.out.println("done!")
You can use a ThreadPoolExecutor
with a pool size set to System.getRuntime().availableProcessors()
Java 6 or Runtime.getRuntime().availableProcessors()
Java 8 and .execute()
it all the tasks you want to execute, then call tpe.shutdown()
and then wait in a while(!tpe.terminated()) { /* waiting for all tasks to complete */}
which blocks for all the submitted tasks to complete. where tpe
is a reference to your ThreadPoolExecutor
instance.
Or if it is more appropriate use an ExecutorCompletionService A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.