起
原文地址 http://blog.csdn.net/qq_25806863/article/details/71743659
在之前說過睛蛛,線程池ThreadPoolExecutor可以調(diào)用submit方法來獲取返回值Future。像下面這樣:
這里先定義三個Callable,之后都用這三個:
Callable callable1 = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "我是call1的返回值";
}
};
Callable callable2 = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
return "我是call2的返回值";
}
};
Callable callable3 = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "我是call3的返回值";
}
};
直接使用ThreadPoolExecutor的submit獲取結(jié)果的使用方法是這樣的:
//聲明一個線程池
ExecutorService executor = Executors.newFixedThreadPool(5);
//提交三個任務(wù)
Future future1 = executor.submit(callable1);
Future future2 = executor.submit(callable2);
Future future2 = executor.submit(callable2);
//開始獲取返回值
System.out.println("兩個任務(wù)提交完畢,開始獲取結(jié)果 "+getStringDate());
System.out.println(future1.get()+" "+getStringDate());
System.out.println(future2.get()+" "+getStringDate());
System.out.println(future3.get()+" "+getStringDate());
System.out.println("獲取結(jié)果完畢 "+getStringDate());
根據(jù)之前的理解,get()
方法是有阻塞性的,因為future1的任務(wù)執(zhí)行時間是5秒,所以在future1.get()
這行代碼上會阻塞5秒苗踪,然后才會獲取到結(jié)果,繼續(xù)往下執(zhí)行削锰。而在5秒內(nèi)future2和future3的任務(wù)已經(jīng)執(zhí)行完了通铲,所以會立馬得到結(jié)果。
真實輸出也是這樣:
明明future2和future3的任務(wù)早就執(zhí)行完了器贩,卻被future1.get()
方法阻塞了颅夺。
使用CompletionService可以作為一種解決方法朋截。
CompletionService簡介
CompletionService的主要功能就是一邊生成任務(wù),一邊獲取任務(wù)的返回值碗啄。讓兩件事分開執(zhí)行质和,任務(wù)之間不會互相阻塞。
CompletionService在提交任務(wù)之后稚字,會根據(jù)任務(wù)完成順序來獲取返回值饲宿,也就是誰先完成就返回誰的返回值。
CompletionService是一個接口:
public interface CompletionService<V> {
Future<V> submit(Callable<V> var1);
Future<V> submit(Runnable var1, V var2);
Future<V> take() throws InterruptedException;
Future<V> poll();
Future<V> poll(long var1, TimeUnit var3) throws InterruptedException;
}
CompletionService只有一個實現(xiàn)類胆描,就是ExecutorCompletionService
我這里有兩個是因為用的AndroidStudio瘫想,一個是java的SDK的一個是Android的SDK的。
ExecutorCompletionService的使用
CompletionService接口一共也就定義了那么幾個方法昌讲,submit方法和ExecutorService的submit沒什么不同国夜。
下面主要分析一下take()
方法和poll()
方法
構(gòu)造方法
ExecutorCompletionService的構(gòu)造方法有兩個:
public ExecutorCompletionService(Executor var1)
ExecutorCompletionService(Executor var1, BlockingQueue<Future<V>> var2)
由此可見,CompletionService對任務(wù)的各種操作還是通過Executor來實現(xiàn)的短绸,一般就是ThreadPoolExecutor车吹。
下面是一個簡單例子:
還是用一開始的三個Callable,這次用CompletionService來提交任務(wù)并獲取結(jié)果醋闭。
//新建一個線程池executor
ExecutorService executor = Executors.newFixedThreadPool(5);
//用線程池executor新建一個CompletionService
CompletionService completionService = new ExecutorCompletionService(executor);
//用CompletionService提交任務(wù)
completionService.submit(callable1);
completionService.submit(callable2);
completionService.submit(callable3);
//用CompletionService獲取結(jié)果
System.out.println("兩個任務(wù)提交完畢窄驹,開始獲取結(jié)果 "+getStringDate());
System.out.println(completionService.take().get()+" "+getStringDate());
System.out.println(completionService.take().get()+" "+getStringDate());
System.out.println(completionService.take().get()+" "+getStringDate());
System.out.println("獲取結(jié)果完畢 "+getStringDate());
可以看下輸出:
雖然提交的順序是1,2证逻,3乐埠,但是獲取結(jié)果的時候是按任務(wù)完成順序來獲取的,所以結(jié)果是3囚企,2丈咐,1.
take()方法
其實take()方法也是一個阻塞方法,調(diào)用這個方法時龙宏,他會一直等待直到線程池中返回一個結(jié)果棵逊,哪個任務(wù)先完成,就返回哪個任務(wù)的結(jié)果烦衣。
在上面的例子中歹河,由于callable3是最先完成的,所以最先拿到的值就是callable3的返回值花吟。
因為剛好提交了3個任務(wù),調(diào)用了3次take()方法厨姚,因此剛好能拿到全部的任務(wù)的結(jié)果衅澈。
如果在調(diào)用一次take()方法,那么就會因為等不到有任務(wù)返回結(jié)果而阻塞在那里:
例如值提交一個任務(wù)谬墙,而調(diào)用兩次take()方法今布,那么程序就會阻塞在第二個take()方法那里等待一個結(jié)果
ExecutorService executor = Executors.newFixedThreadPool(5);
CompletionService completionService = new ExecutorCompletionService(executor);
completionService.submit(callable1);
System.out.println("兩個任務(wù)提交完畢经备,開始獲取結(jié)果 "+getStringDate());
System.out.println(completionService.take().get()+" "+getStringDate());
System.out.println(completionService.take().get()+" "+getStringDate());
System.out.println("獲取結(jié)果完畢 "+getStringDate());
結(jié)果會一直是這樣
poll()方法和poll(long var1, TimeUnit var3)方法
Poll()方法也是獲取返回值,使用方法也跟take()一樣部默。
而poll()方法和take()方法的區(qū)別就是侵蒙,poll()方法不會阻塞的去等結(jié)果,而是如果調(diào)用poll()方法的時候沒有結(jié)果可以獲取就直接返回一個null傅蹂,然后程序繼續(xù)往下運行纷闺。
這時如果調(diào)用poll().get()可能會引發(fā)空指針異常java.lang.NullPointerException
例子:
依舊是一開始那三個任務(wù),在循環(huán)中連續(xù)調(diào)用8次poll()方法份蝴,每次間隔1秒鐘:
ExecutorService executor = Executors.newFixedThreadPool(5);
CompletionService completionService = new ExecutorCompletionService(executor);
completionService.submit(callable1);
completionService.submit(callable2);
completionService.submit(callable3);
System.out.println("兩個任務(wù)提交完畢犁功,開始獲取結(jié)果 "+getStringDate());
for (int i = 0; i < 8; i++) {
Future future = completionService.poll();
if (future!=null){
//如果future為空,會引發(fā) NullPointerException
System.out.println(future.get() + getStringDate());
}else {
System.out.println(future+" "+getStringDate());
}
Thread.sleep(1000);
}
System.out.println("獲取結(jié)果完畢 "+getStringDate());
輸出:
每次調(diào)用都是立馬返回婚夫,毫不猶豫浸卦。所以沒有結(jié)果的時候就返回空。
而poll(long var1, TimeUnit var3)方法就相當(dāng)于給他強制設(shè)置了一個等待時間案糙,你如果拿不到結(jié)果就等這么久限嫌,等這么久還拿不到再返回null。
把上面的循環(huán)改成這樣:
for (int i = 0; i < 8; i++) {
Future future = completionService.poll(1, TimeUnit.SECONDS);
if (future!=null){
System.out.println(future.get() + getStringDate());
}else {
System.out.println(future+" "+getStringDate());
}
}
不在睡眠了时捌,每次調(diào)用poll()方法個體1秒的等待時間。
這里第一次調(diào)用就等了1秒匣椰,然后在1秒內(nèi)等到了call3的返回值,就返回call3的返回值禽笑。
第二次循環(huán)又等了一秒入录,一秒內(nèi)沒有獲得結(jié)果僚稿,返回null。