![](/img/trans.png)
[英]How to check if all tasks running on ExecutorService are completed
[英]How to know whether there're running tasks in ExecutorService in java?
我想让程序继续,直到ExecutorService中的所有任务完成。 而且我不想关闭它,我稍后再使用它。 我怎样才能做到这一点? 谢谢
使用ExecutorService#shutdown()
后跟ExecutorService#awaitTermination()
使main
线程在退出之前等待所有提交的任务完成。 来自文档
ExecutorService的#awaitTermination()
阻止所有任务在关闭请求之后完成执行,或者发生超时,或者当前线程被中断,以先发生者为准。
直接从ExecutorService
Javadoc获取的示例:
http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
以下方法分两个阶段关闭ExecutorService,首先调用shutdown以拒绝传入的任务,然后在必要时调用shutdownNow以取消任何延迟的任务:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.