Possible Duplicates:
ExecutorService, how to wait for all tasks to finish
Java ExecutorService: awaitTermination of all recursively created tasks
有没有办法阻塞当前线程,直到 ExecutorService
完成它的所有任务?
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!")
对于你所有的任务,将它们放入一个 List callables 然后在它们上调用 All
ExecutorService e = ...
e.invokeAll(callables);
根据 javadocs
Executes the given tasks, returning a
list of Futures holding their status
and results when all complete.
Future.isDone() is true for each
element of the returned list. Note
that a completed task could have
terminated either normally or by
throwing an exception. The results of
this method are undefined if the given
collection is modified while this
operation is in progress.
因此线程会一直等到所有任务都完成