CompletableFuture: 分析一

CompletableFuture 实现了Futurn, CompletionStage,而CompletionStage有好多方法,需要慢慢探究,此次记录仅为CompletableFuture探索记录之一

先看部分源码:

public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {.....}
 public static void main(String[] args) {
        Integer result = CompletableFuture.supplyAsync(() -> {
            int a = 1;
            for (int i = 0; i < 10; i++) {
                a++;
                System.out.println(Thread.currentThread().getName() + " a++ " + a);
                try {
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return a;
        }).thenCombineAsync(CompletableFuture.supplyAsync(() -> {
            int b = 1;
            for (int i = 0; i < 10; i++) {
                b++;
                System.out.println(Thread.currentThread().getName() + " b++ " + b);
                try {
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return b;
        }), (a, b) -> a + b).join();

        System.out.println(result);

运行结果:

ForkJoinPool.commonPool-worker-1 a++ 2
ForkJoinPool.commonPool-worker-2 b++ 2
ForkJoinPool.commonPool-worker-1 a++ 3
ForkJoinPool.commonPool-worker-2 b++ 3
ForkJoinPool.commonPool-worker-2 b++ 4
ForkJoinPool.commonPool-worker-1 a++ 4
ForkJoinPool.commonPool-worker-1 a++ 5
ForkJoinPool.commonPool-worker-2 b++ 5
ForkJoinPool.commonPool-worker-1 a++ 6
ForkJoinPool.commonPool-worker-2 b++ 6
ForkJoinPool.commonPool-worker-1 a++ 7
ForkJoinPool.commonPool-worker-2 b++ 7
ForkJoinPool.commonPool-worker-1 a++ 8
ForkJoinPool.commonPool-worker-2 b++ 8
ForkJoinPool.commonPool-worker-1 a++ 9
ForkJoinPool.commonPool-worker-2 b++ 9
ForkJoinPool.commonPool-worker-2 b++ 10
ForkJoinPool.commonPool-worker-1 a++ 10
ForkJoinPool.commonPool-worker-1 a++ 11
ForkJoinPool.commonPool-worker-2 b++ 11
22

可以看到两个supplyAsync()是异步在执行, thenCombineAsync()是合并异步执行完的结果

原文地址:https://www.cnblogs.com/spring20190213dream/p/12034271.html