美文网首页
主要并发工具类-CompletionService的使用

主要并发工具类-CompletionService的使用

作者: 飞奔吧牛牛 | 来源:发表于2020-02-13 15:44 被阅读0次

这个类,不太好解释。注释上这样写道:
A service that decouples the production of new asynchronous tasks from the consumption of the results of completed tasks. Producer submit tasks for execution. Consumers take completed tasks and process their results in the order they complete. 巴拉巴拉巴拉。。。。
意思就是说将异步任务的生产和结果进行解耦。注意:是按完成任务的顺序进行对任务结果进行处理。
首先得知道什么叫不按完成顺序对结果进行处理。

 ExecutorService pool = Executors.newFixedThreadPool(5);
        Future<String> futureA = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(5);
                return "A";
            }
        });
        Future<String> futureB = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(2);
                return "B";
            }
        });
        System.out.println(futureA.get());
        System.out.println(futureB.get());
//打印结果
A
B

程序中futrueB中的任务先运行完毕,本可以先获取结果,但程序阻塞在futureA.get()处,等futureA.get()获取结果后才执行futureB.get()拿到结果。
如果希望有任务返回后就立刻拿到结果,就需要用到CompletionService了。

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletionService<String> service = new ExecutorCompletionService<>(executorService);
        service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(2);
                return "A";
            }
        });
        service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(3);
                return "B";
            }
        });
        service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(1);
                return "C";
            }
        });
        String result;
        while ((result = service.take().get()) != null) {
            System.out.println(result);
        }

//打印结果
C
A
B

哪一个任务先返回结果就先处理该结果。

相关文章

网友评论

      本文标题:主要并发工具类-CompletionService的使用

      本文链接:https://www.haomeiwen.com/subject/srtlfhtx.html