CompletableFuture-对计算结果进行消费

package com.nanjing.gulimall.zhouyimo.test;

import java.util.concurrent.*;

/**
 * @author zhou
 */
public class CompletableFutureAPI2Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            return 1;
        }, threadPool).thenApply(f -> {
            return f + 2;
        }).thenApply(f -> {
            return f + 3;
        }).thenAccept(r -> {
            System.out.println(r);//6
        });
        System.out.println(Thread.currentThread().getName() + "------主线程先去做其他事情");
        threadPool.shutdown();
    }
}


6
main------主线程先去做其他事情

package com.nanjing.gulimall.zhouyimo.test;

import java.util.concurrent.*;

/**
 * @author zhou
 */
public class CompletableFutureAPI2Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        /*System.out.println(CompletableFuture.supplyAsync(() -> {
            return "result";},threadPool).thenRun(() -> {}).join());*/
        //换Lambda简洁的写法,省略return
        System.out.println(CompletableFuture.supplyAsync(() -> "result",threadPool).thenRun(() -> {}).join());//null
        System.out.println(CompletableFuture.supplyAsync(() -> "result",threadPool).thenAccept(r -> System.out.println(r)).join());//result  null
        System.out.println(CompletableFuture.supplyAsync(() -> "result",threadPool).thenApply(f -> f + 2).join());//result2
        System.out.println(Thread.currentThread().getName() + "------主线程先去做其他事情");
        threadPool.shutdown();
    }
}

你可能感兴趣的:(JUC并发编程与源码分析,java)