CompletableFuture: 分析一

Posted spring20190213dream

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()是合并异步执行完的结果

以上是关于CompletableFuture: 分析一的主要内容,如果未能解决你的问题,请参考以下文章

CompletableFuture源码分析以及例子实证

码片速率的含义

CDMA码片序列问题

转载 WCDMA中码片速率符号速率bit速率 WCDMA常用概念

码分复用

Servlet的调试