![](/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.