CompletionService和ExecutorCompletionService

CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象。
 
如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果。为此你可以将每个任务的Future保存进一个集合,然后循环这个集合调用Future的get()取出数据。幸运的是CompletionService帮你做了这件事情。
 
CompletionService整合了Executor和BlockingQueue的功能。你可以将Callable任务提交给它去执行,然后使用类似于队列中的take和poll方法,在结果完整可用时获得这个结果,像一个打包的Future。
 
CompletionService的take返回的future是哪个先完成就先返回哪一个,而不是根据提交顺序。
 
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);
        for (int i = 1; i <= 10; i++) {
            final int seq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            try {
                // 取出并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。
                Integer seq = completionService.take().get();
                System.out.println("第" + seq + "个任务返回");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
第4个任务返回
第5个任务返回
第3个任务返回
第7个任务返回
第10个任务返回
第2个任务返回
第8个任务返回
第9个任务返回
第1个任务返回
第6个任务返回
原文地址:https://www.cnblogs.com/tinya/p/8452780.html