ExecutorService的關閉
shutdown和awaitTermination為接口ExecutorService定義的兩個方法,一般情況配合使用來關閉線程池。
方法簡介
shutdown方法:平滑的關閉ExecutorService,當此方法被調用時,ExecutorService停止接收新的任務并且等待已經提交的任務(包含提交正在執行和提交未執行)執行完成。當所有提交任務執行完畢,線程池即被關閉。
awaitTermination方法:接收人timeout和TimeUnit兩個參數,用于設定超時時間及單位。當等待超過設定時間時,會監測ExecutorService是否已經關閉,若關閉則返回true,否則返回false。一般情況下會和shutdown方法組合使用。
具體實例
普通任務處理類:
package com.secbro.test.thread;import java.util.concurrent.Callable;/*** @author zhuzhisheng* @Description* @date on 2016/6/1.*/ public class Task implements Callable{@Overridepublic Object call() throws Exception {System.out.println("普通任務");return null;} }
長時間任務處理類:
package com.secbro.test.thread;import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit;/*** @author zhuzhisheng* @Description* @date on 2016/6/1.*/ public class LongTask implements Callable{@Overridepublic Object call() throws Exception {System.out.println("長時間任務");TimeUnit.SECONDS.sleep(5);return null;} }
測試類:
package com.secbro.test.thread;import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;/*** @author zhuzhisheng* @Description* @date on 2016/6/1.*/ public class TestShutDown {public static void main(String[] args) throws InterruptedException{ScheduledExecutorService service = Executors.newScheduledThreadPool(4);service.submit(new Task());service.submit(new Task());service.submit(new LongTask());service.submit(new Task());service.shutdown();while (!service.awaitTermination(1, TimeUnit.SECONDS)) {System.out.println("線程池沒有關閉");}System.out.println("線程池已經關閉");}}
輸出結果為:
普通任務
普通任務
長時間任務
普通任務
線程池沒有關閉
線程池沒有關閉
線程池沒有關閉
線程池沒有關閉
線程池已經關閉
?