CompletionService应用

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(5);
        CompletionService<Integer> cs = new ExecutorCompletionService<>(service);
        cs.submit(()->getPriceByS1());
        cs.submit(()->getPriceByS2());
        cs.submit(()->getPriceByS3());

        for (int i = 0; i < 3; i++) {
            Integer integer = cs.take().get();
            service.execute(() -> save(integer));
        }

        service.shutdown();
    }

    public static void save(Integer r){
        log.info("保存询价结果:{}",r);
    }

    public static Integer getPriceByS1() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(5000);
        log.info("电商s1的价格1200");
        return 1200;
    }

    public static Integer getPriceByS2() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(8000);
        log.info("电商s2的价格1000");
        return 1000;
    }

    public static Integer getPriceByS3() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(3000);
        log.info("电商s3的价格800");
        return 800;
    }

执行结果
CompletionService应用

上一篇:正则表达式 findall()与match()的区别


下一篇:C# DevExpress GridControl下动态创建列的方法