zoukankan      html  css  js  c++  java
  • 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()是合并异步执行完的结果

  • 相关阅读:
    数组作为方法参数
    定义一个方法,根据商品总价,计算出对应的折扣并输出。折扣信息如下
    Cocos2d入门--1--初涉相关属性或代码
    JSP基础--JAVA遇见HTML
    查找算法--折半查找
    排序算法--冒泡排序
    排序算法--简单选择排序
    C语言的传值与传址调用
    学习C语言的数组
    如何获取QQ里的截图app?
  • 原文地址:https://www.cnblogs.com/spring20190213dream/p/12034271.html
Copyright © 2011-2022 走看看