我正在创建一个线程池执行器,并希望它在继续之前完成所有任务: 例如:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
taskExecutor.execute(new MyTask());
taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
最佳答案
有多种方法可以做到这一点:
但最流行的是使用 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();
}
}
关于java - 如何等待线程池完成所有任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769004/