轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/27250059
一般情況下,我們使用Runnable作為基本的任務表示形式,但是Runnable是一種有很大局限的抽象,run方法中只能記錄日誌,列印,或者把資料匯總入某個容器(一方面記憶體消耗大,另一方面需要控制同步,效率很大的限制),總之不能返回執行的結果;比如同時1000個任務去網路上抓取資料,然後將抓取到的資料進行處理(處理方式不定),我覺得最好的方式就是提供回調介面,把處理的方式最為回調傳進去;但是現在我們有了更好的方式實現:CompletionService + Callable
Callable的call方法可以返回執行的結果;
CompletionService將Executor(線程池)和BlockingQueue(阻塞隊列)結合在一起,同時使用Callable作為任務的基本單元,整個過程就是生產者不斷把Callable任務放入阻塞對了,Executor作為消費者不斷把任務取出來執行,並返回結果;
優勢:
a、阻塞隊列防止了記憶體中排隊等待的任務過多,造成記憶體溢出(畢竟一般生產者速度比較快,比如爬蟲準備好網址和規則,就去執行了,執行起來(消費者)還是比較慢的)
b、CompletionService可以實現,哪個任務先執行完成就返回,而不是按順序返回,這樣可以極大的提升效率;
1、CompletionService : Executor + BlockingQueue
下面看個例子:
package com.zhy.concurrency.completionService;import java.util.Random;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Callable;import java.util.concurrent.CompletionService;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorCompletionService;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.LinkedBlockingDeque;/** * 將Executor和BlockingQueue功能融合在一起,可以將Callable的任務提交給它來執行, 然後使用take()方法獲得已經完成的結果 * * @author zhy * */public class CompletionServiceDemo{public static void main(String[] args) throws InterruptedException,ExecutionException{/** * 內部維護11個線程的線程池 */ExecutorService exec = Executors.newFixedThreadPool(11);/** * 容量為10的阻塞隊列 */final BlockingQueue<Future<Integer>> queue = new LinkedBlockingDeque<Future<Integer>>(10);//執行個體化CompletionServicefinal CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(exec, queue);/** * 類比瞬間產生10個任務,且每個任務執行時間不一致 */for (int i = 0; i < 10; i++){completionService.submit(new Callable<Integer>(){@Overridepublic Integer call() throws Exception{int ran = new Random().nextInt(1000);Thread.sleep(ran);System.out.println(Thread.currentThread().getName()+ " 休息了 " + ran);return ran;}});}/** * 立即輸出結果 */for (int i = 0; i < 10; i++){try{//誰最先執行完成,直接返回Future<Integer> f = completionService.take();System.out.println(f.get());} catch (InterruptedException e){e.printStackTrace();} catch (ExecutionException e){e.printStackTrace();}}exec.shutdown();}}輸出結果:
pool-1-thread-4 休息了 5252pool-1-thread-1 休息了 5959pool-1-thread-10 休息了 215215pool-1-thread-9 休息了 352352pool-1-thread-5 休息了 389389pool-1-thread-3 休息了 589589pool-1-thread-2 休息了 794794pool-1-thread-7 休息了 805805pool-1-thread-6 休息了 909909pool-1-thread-8 休息了 987987
最先執行完成的直接返回,並不需要按任務提交的順序執行,如果需要寫個高並發的程式,且每個任務需要返回執行結果,這是個相當不錯的選擇!
2、ExecutorService.invokeAll
ExecutorService的invokeAll方法也能批量執行任務,並批量返回結果,但是呢,有個我覺得很致命的缺點,必須等待所有的任務執行完成後統一返回,一方面記憶體持有的時間長;另一方面響應性也有一定的影響,畢竟大家都喜歡看看刷刷的執行結果輸出,而不是苦苦的等待;
下面看個例子:
package com.zhy.concurrency.executors;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class TestInvokeAll{public static void main(String[] args) throws InterruptedException,ExecutionException{ExecutorService exec = Executors.newFixedThreadPool(10);List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();Callable<Integer> task = null;for (int i = 0; i < 10; i++){task = new Callable<Integer>(){@Overridepublic Integer call() throws Exception{int ran = new Random().nextInt(1000);Thread.sleep(ran);System.out.println(Thread.currentThread().getName()+" 休息了 " + ran );return ran;}};tasks.add(task);}long s = System.currentTimeMillis();List<Future<Integer>> results = exec.invokeAll(tasks);System.out.println("執行任務消耗了 :" + (System.currentTimeMillis() - s) +"毫秒");for (int i = 0; i < results.size(); i++){try{System.out.println(results.get(i).get());} catch (Exception e){e.printStackTrace();}}exec.shutdown();}}
執行結果:
pool-1-thread-10 休息了 1pool-1-thread-5 休息了 59pool-1-thread-6 休息了 128pool-1-thread-1 休息了 146pool-1-thread-3 休息了 158pool-1-thread-7 休息了 387pool-1-thread-9 休息了 486pool-1-thread-8 休息了 606pool-1-thread-4 休息了 707pool-1-thread-2 休息了 817執行任務消耗了 :819毫秒146817158707591283876064861
我特意在任務提交完成列印了一個時間,然後invokeAll執行完成後列印了下時間,可以看出invokeAll返回是等待所有線程執行完畢的。這點來說,我覺得可用性不如CompletionService。
嗯,對於批量執行任務,且攜帶返回結果的案例就到這裡~如果有疑問或者代碼中存在錯誤請指出~