閱讀679 返回首頁    go 技術社區[雲棲]


ExecutorService對象的shutdown()和shutdownNow()的區別

可以關閉 ExecutorService,這將導致其拒絕新任務。提供兩個方法來關閉 ExecutorService。shutdown() 方法在終止前允許執行以前提交的任務,而 shutdownNow() 方法阻止等待任務啟動並試圖停止當前正在執行的任務。在終止時,執行程序沒有任務在執行,也沒有任務在等待執行,並且無法提交新任務。應該關閉未使用的 ExecutorService 以允許回收其資源。 

下列方法分兩個階段關閉 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();
   }
 }


shutdown調用後,不可以再submit新的task,已經submit的將繼續執行。

shutdownNow試圖停止當前正執行的task,並返回尚未執行的task的list

最後更新:2017-04-03 18:52:10

  上一篇:go Android 向多媒體數據庫增加音頻文件
  下一篇:go Android MediaStore 與Media.EXTERNAL_CONTENT_URI