Java8之CompletableFuture async的理解

验证代码如下

ExecutorService executorService = Executors.newFixedThreadPool(3);
        //executorService.submit(new RuleTestRunnable(1));
        List taskList = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            taskList.add(i);
        }
        CompletableFuture a1 = CompletableFuture.supplyAsync(() -> {
            logger.info("线程1{}{}","开始");

            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("线程1{}{}","结束");
            return "1";
        },executorService);
       CompletableFuture a2 = CompletableFuture.supplyAsync(() -> {

            logger.info("线程2{}{}","开始");
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("线程2{}{}","结束");
            return "1";
        },executorService);
        CompletableFuture a= a1.thenCombineAsync(a2,(s1,s2) -> {
            logger.info("组合线程{}{}");
            return  s1+s2;
        },executorService);
        Object result = a.get(); 
  

 

当executorService线程池大小为2时候,执行结果如下:

[pool-4-thread-1] INFO test.rcd.thread.CompletableFutureDemo.lambda$mains$4:127 - 组合线程{}{}

a1.thenCombineAsync方法始终被线程1或2执行,

当executorService线程池大小为3时候,执行结果如下:

[pool-4-thread-3] INFO test.rcd.thread.CompletableFutureDemo.lambda$mains$4:127 - 组合线程{}{}

a1.thenCombineAsync方法始终被线程3执行,

改为a1.thenCombine(),执行结果:

a1.thenCombineAsync方法始终被线程1或2执行,

由此可见,async方法始终尝试取新线程执行方法,不带async方法则会从当前线程里取线程执行.CompletableFuture似是与线程无关的.

欢迎指教

交流方式

QQ:1

 

 

你可能感兴趣的:(jdk8)