final List<Callable<Boolean>> tasks = new ArrayList<>(10);
for (int i=0;i<10;i++) tasks.add(()->{
//something time consuming
return true;
});
final ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<Boolean> handles = executor.invokeAll(tasks);
for (Future<Boolean> handle : handles) {
handle.get();
}
// here all the 10 tasks have been completed by the 5 thread pool
1 回答
拥有ExecutorService的重点不在于处理线程,所以除非你有一个非常具体的理由来跟踪它们的状态,否则你应该避免这样做 .
您还可以向池中添加任意数量的任务,执行程序将全部运行它们 .
例如:
请注意,每次调用handle.get()返回时,池中的线程理论上都可用,但执行程序将立即重用它来运行下一个等待任务 .