我正在创建线程池执行器,并希望它在继续之前完成所有任务: 例如:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
taskExecutor.execute(new MyTask());
taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
答案 0 :(得分:1)
有多种方法可以这样做:
但是最受欢迎的一种是使用threadpool.shutdown():
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
threadPool.shutdown();
try {
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
} catch (InterruptedException ex) {
threadPool.shutdownNow();
Thread.currentThread().interrupt();
}
}
答案 1 :(得分:1)
与书面答案不同,在这种情况下,人们通常不知道工作何时完成。根据经验,更好的方法是从正在运行的任务中进行回调。
您可以这样做,如下所示:
class MyTask implements Callable {...}//and do your task inside the "call" method
然后:
List<MyTask> allMyTasks // have all your tasks piled up
List<Future<TaskOutPut>> futures = taskExecutor.invokeAll(allMyTasks);
List<TaskOutPut> output = futures.map(future->future.get()).collect(Collectors.toList()); //this will make sure every future is completed