![](/img/trans.png)
[英]Why do we need to use awaitTermination but not just shutdownNow()?
[英]Do we need to call awaitTermination on ScheduledExecutorService?
嗨,我是Java多線程新手。 我有成千上萬的計划任務/線程需要執行。 我使用以下代碼
ScheduledExecutorSerivce scheduleService = Executors.newScheduledThreadPool(90);
Map<Interger,Interger> loginMap = new HashMap<>();//contain login time of scheduled threads
for(int i = 0; i < taskCount ; i++) {
scheduleService.schedule(new MyCallableWorker(),loginMap.get(i),TimeUnit.SECONDS)
}
scheduleService.shutdown();
//do I need to call the following because I dont know any timeout value or above shutDown() is enough
while(!scheduleService.isTerminated()) {
}
另請告訴我什么是線程池的理想計數。 我已設置為90但我想要可以根據需要增長的池,但看起來像ScheduleExecutorService沒有這樣的API。 請提前指導謝謝。
scheduleService.shutdown();
將指示調度程序不應該接受新任務,現有的任務將被取消,或者它們可能被執行(但不會重復),具體取決於所使用的策略:
“如果已將ExecuteExistingDelayedTasksAfterShutdownPolicy設置為false,則取消延遲尚未過去的現有延遲任務。除非將ContinueExistingPeriodicTasksAfterShutdownPolicy設置為true,否則將取消現有定期任務的后續執行。”
現在在您的代碼中,您應該致電:
scheduleSerice.awaitTermination()
而不是while(!scheduleService.isTerminated())
。 while循環將燒毀處理器的所有周期,因為它將不斷檢查執行程序狀態。
如果你沒有調用awaitTermination方法(或你的循環aproach),你調用shceduleService.schedule的方法將完成(退出),並且可能你的整個程序將終止(不完成作業)。
但這取決於你的設計。 如果它是異步的,那么你可以簡單地忽略awaitteration並繼續你的工作。 這些工作將在后台處理。
你的線程池不應該增長!!!! 它應該與您的avaialbe資源== CPU匹配。 對於正在等待資源的IO任務而言,它應該在處理器計數周圍,對於IO任務來說,CPU的數量加倍,任何更多的事情都沒有意義,它實際上會減慢執行速度,因為會有線程推進。
池大小限制了將同時執行的任務數,而不是任務隊列的大小,除非另外設置,否則它是無限制的並且增長。
如果應用程序在確保所有當前任務完成后應該執行某些操作,則需要調用awaitTermination()
。 如果您的應用程序不關心當前任務何時完成,那么您不需要awaitTermination()
。
關於增加線程池大小,您可以直接使用ScheduledThreadPoolExecutor
。
/**
* Creates a new {@code ScheduledThreadPoolExecutor} with the
* given core pool size.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}
保持核心池大小至少是您所需要的,並讓它增長到最大池大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.