ExecutorService——shutdown方法和awaitTermination方法
ExecutorService的關(guān)閉
shutdown和awaitTermination為接口ExecutorService定義的兩個(gè)方法,一般情況配合使用來(lái)關(guān)閉線程池。
方法簡(jiǎn)介
shutdown方法:平滑的關(guān)閉ExecutorService,當(dāng)此方法被調(diào)用時(shí),ExecutorService停止接收新的任務(wù)并且等待已經(jīng)提交的任務(wù)(包含提交正在執(zhí)行和提交未執(zhí)行)執(zhí)行完成。當(dāng)所有提交任務(wù)執(zhí)行完畢,線程池即被關(guān)閉。
awaitTermination方法:接收人timeout和TimeUnit兩個(gè)參數(shù),用于設(shè)定超時(shí)時(shí)間及單位。當(dāng)?shù)却^(guò)設(shè)定時(shí)間時(shí),會(huì)監(jiān)測(cè)ExecutorService是否已經(jīng)關(guān)閉,若關(guān)閉則返回true,否則返回false。一般情況下會(huì)和shutdown方法組合使用。
具體實(shí)例
普通任務(wù)處理類:
長(zhǎng)時(shí)間任務(wù)處理類:
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("長(zhǎng)時(shí)間任務(wù)");TimeUnit.SECONDS.sleep(5);return null;} }測(cè)試類:
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("線程池沒(méi)有關(guān)閉");}System.out.println("線程池已經(jīng)關(guān)閉");}}輸出結(jié)果為:
普通任務(wù) 普通任務(wù) 長(zhǎng)時(shí)間任務(wù) 普通任務(wù) 線程池沒(méi)有關(guān)閉 線程池沒(méi)有關(guān)閉 線程池沒(méi)有關(guān)閉 線程池沒(méi)有關(guān)閉 線程池已經(jīng)關(guān)閉?
總結(jié)
以上是生活随笔為你收集整理的ExecutorService——shutdown方法和awaitTermination方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JavaScript 学习提升
- 下一篇: web第6次作业position