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

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

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

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        CompletionService 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;
    }

你可能感兴趣的:(CompletionService异步和阻塞队列的结合工具类)