Java并發專題 帶返回結果的批量任務執行 CompletionService ExecutorService.invokeAll

jopen 8年前發布 | 16K 次閱讀 Java開發

轉載請標明出處: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);
        //實例化CompletionService
        final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
                exec, queue);

        /**
         * 模擬瞬間產生10個任務,且每個任務執行時間不一致
         */
        for (int i = 0; i < 10; i++)
        {
            completionService.submit(new Callable<Integer>()
            {
                @Override
                public 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 休息了 52
52
pool-1-thread-1 休息了 59
59
pool-1-thread-10 休息了 215
215
pool-1-thread-9 休息了 352
352
pool-1-thread-5 休息了 389
389
pool-1-thread-3 休息了 589
589
pool-1-thread-2 休息了 794
794
pool-1-thread-7 休息了 805
805
pool-1-thread-6 休息了 909
909
pool-1-thread-8 休息了 987
987

最先執行完成的直接返回,并不需要按任務提交的順序執行,如果需要寫個高并發的程序,且每個任務需要返回執行結果,這是個相當不錯的選擇!


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>()
            {
                @Override
                public 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 休息了 1
pool-1-thread-5 休息了 59
pool-1-thread-6 休息了 128
pool-1-thread-1 休息了 146
pool-1-thread-3 休息了 158
pool-1-thread-7 休息了 387
pool-1-thread-9 休息了 486
pool-1-thread-8 休息了 606
pool-1-thread-4 休息了 707
pool-1-thread-2 休息了 817
執行任務消耗了 :819毫秒
146
817
158
707
59
128
387
606
486
1

我特意在任務提交完成打印了一個時間,然后invokeAll執行完成后打印了下時間,可以看出invokeAll返回是等待所有線程執行完畢的。這點來說,我覺得可用性不如CompletionService。


嗯,對于批量執行任務,且攜帶返回結果的案例就到這里~如果有疑問或者代碼中存在錯誤請指出~




來自: http://blog.csdn.net//lmj623565791/article/details/27250059

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!