CompletionService异步和阻塞队列的结合工具类

当你有多个任务,先执行完的放入一个阻塞队列,,然后再从阻塞队列里面取出数据

 /**
     * 
     * @param args
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        CompletionService<Integer> cs = new ExecutorCompletionService<>(executorService);

         cs.submit(() -> getPriceByS1());

        cs.submit(() -> getPriceByS2());

        cs.submit(() -> getPriceByS3());

        for (int i = 0; i <3 ; i++) {
            Integer r = cs.take().get();
            executorService.execute(()-> System.out.println(r));
        }
        executorService.shutdown();



    }

    static Integer getPriceByS1() throws InterruptedException {
        Thread.sleep(1000);
        return 1000;
    }
    static Integer getPriceByS2() throws InterruptedException {
        Thread.sleep(500);
        return 500;
    }
    static Integer getPriceByS3() throws InterruptedException {
        Thread.sleep(2000);
        return 2000;
    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容