ExecutorService对象的shutdown()和shutdownNow()的区别
生活随笔
收集整理的這篇文章主要介紹了
ExecutorService对象的shutdown()和shutdownNow()的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
可以關閉?ExecutorService,這將導致其拒絕新任務。提供兩個方法來關閉?ExecutorService。shutdown()?方法在終止前允許執行以前提交的任務,而?shutdownNow()?方法阻止等待任務啟動并試圖停止當前正在執行的任務。在終止時,執行程序沒有任務在執行,也沒有任務在等待執行,并且無法提交新任務。應該關閉未使用的?ExecutorService?以允許回收其資源。?
下列方法分兩個階段關閉?ExecutorService。第一階段調用?shutdown?拒絕傳入任務,然后調用?shutdownNow(如有必要)取消所有遺留的任務:?
1 void shutdownAndAwaitTermination(ExecutorService pool) { 2 pool.shutdown(); // Disable new tasks from being submitted 3 try { 4 // Wait a while for existing tasks to terminate 5 if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { 6 pool.shutdownNow(); // Cancel currently executing tasks 7 // Wait a while for tasks to respond to being cancelled 8 if (!pool.awaitTermination(60, TimeUnit.SECONDS)) 9 System.err.println("Pool did not terminate"); 10 } 11 } catch (InterruptedException ie) { 12 // (Re-)Cancel if current thread also interrupted 13 pool.shutdownNow(); 14 // Preserve interrupt status 15 Thread.currentThread().interrupt(); 16 } 17 }shutdown調用后,不可以再submit新的task,已經submit的將繼續執行。
shutdownNow試圖停止當前正執行的task,并返回尚未執行的task的list
轉載于:https://www.cnblogs.com/yuandluck/p/9511515.html
總結
以上是生活随笔為你收集整理的ExecutorService对象的shutdown()和shutdownNow()的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: React篇-报错信息:warning:
- 下一篇: BZOJ3993: [SDOI2015]