• 三、CompletableFuture(二)常见用法


    注:

    方法名以”Async“结尾的区别:(如thenApply和thenApplyAsync)

    thenApply:当前任务的线程继续执行“thenApply”的任务。

    thenApplyAsync:把“thenApplyAsync”这个任务继续交给线程池来进行执行。

    一、获得结果和触发计算

    1、获取结果

    get():同Future的get()。

    get(long timeout, TimeUnit unit):同Future的get()。

    join():同get()。join不报异常,get会报异常。

    getNow(T valueIfAbsent):立即获取计算值,如果未计算完,则返回设定的默认值valueIfAbsent。

    2、主动触发计算

    complete(T value):立即打断异步执行。如果打断成功返回true,此时get会得到设定的默认值value。打断失败返回false,此时get会得到异步执行的结果。

    二、对计算结果进行处理

                ...thenApply(i -> {
                    return i + 2;
                }).handle((i, e) -> {
                    return i + 3;
                })...

    i:上一步的计算结果

    e:异常

    1、thenApply

    计算结果存在依赖关系,step by step。

    由于存在依赖关系,当前步骤异常时,不会继续下一步。

    2、handle

    有异常也可以继续下一步,根据带的异常参数可以进一步处理。

    三、对计算结果进行消费

    thenAccept:接收任务的返回结果,并消费处理,无返回结果。

    四、对计算速度进行选用

    applyToEither:返回最快执行完的结果。最快返回后,其他线程依然会继续执行。

        public static void main(String[] args) {
            try {
                CompletableFuture future = CompletableFuture.supplyAsync(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() + "暂停6秒钟");
                        TimeUnit.SECONDS.sleep(6);
                        System.out.println(Thread.currentThread().getName() + "完成6秒钟");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return 6;
                }).applyToEither(CompletableFuture.supplyAsync(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() + "暂停5秒钟");
                        TimeUnit.SECONDS.sleep(5);
                        System.out.println(Thread.currentThread().getName() + "完成5秒钟");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return 5;
                }), r -> r).applyToEither(CompletableFuture.supplyAsync(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() + "暂停4秒钟");
                        TimeUnit.SECONDS.sleep(4);
                        System.out.println(Thread.currentThread().getName() + "完成4秒钟");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return 4;
                }), r -> r);
    
                System.out.println(future.join());
    
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
            }
        }
    View Code

    五、对计算结果进行合并

    thenCombine:合并多个任务的执行结果。(如调用多个接口合并处理后返回前端)

        public static void main(String[] args) {
            try {
                CompletableFuture future = CompletableFuture.supplyAsync(() -> {
                    return 10;
                }).thenCombine(CompletableFuture.supplyAsync(() -> {
                    return 20;
                }), (r1, r2) -> {
                    return r1 + r2;
                });
    
                System.out.println(future.join());
    
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
            }
        }
    View Code
  • 相关阅读:
    [设计模式整理笔记 五] 创建者模式(Builder)
    ArrayList与List<T>笔记
    asp.net站点URLRewrite小记
    ArrayList Array List<T>性能比较
    C# Socket SSL通讯笔记
    [设计模式整理笔记 六] 工厂模式与创建者模式总结
    [设计模式整理笔记 七] 原型模式(ProtoType)
    实现页面提交时显示"正在处理.."
    [设计模式整理笔记 四] 抽象工厂模式(Abstract Factory)
    在 ASP.NET 中执行 URL 重写 [转MSDN]
  • 原文地址:https://www.cnblogs.com/shiblog/p/15715626.html
Copyright © 2020-2023  润新知