下列方法分兩個階段關閉 ExecutorService。第一階段調用 shutdown 拒絕傳入任務,而後調用 shutdownNow(若有必要)取消全部遺留的任務: java
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的將繼續執行。 spa
shutdownNow試圖中止當前正執行的task,並返回還沒有執行的task的list code