码迷,mamicode.com
首页 > 其他好文 > 详细

CompletableFuture: 分析一

时间:2019-12-13 12:18:44      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:div   exception   integer   方法   join()   结果   实现   oid   分析   

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()是合并异步执行完的结果

CompletableFuture: 分析一

标签:div   exception   integer   方法   join()   结果   实现   oid   分析   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!