可以關閉 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