• java8之CompletableFuture


    Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture,结合了Future的优点,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

    执行任务获取返回值

    ExecutorService threadPool = Executors.newFixedThreadPool(4);
    List<Integer> list = Arrays.asList(1, 2, 3);
     for (Integer integer : list) {
                CompletableFuture.supplyAsync(() -> {
                            try {
                                TimeUnit.SECONDS.sleep(integer);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            return "异步获取结果:" + integer;
                        }, threadPool)
                        .whenCompleteAsync((res, exception) ->
                                System.out.println(res)
                        );
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    执行任务并等待全部任务执行完成后返回

    CompletableFuture.allOf(
                            list.stream()
                                    .map(key ->
                                            CompletableFuture.runAsync(() -> {
                                                try {
                                                    TimeUnit.SECONDS.sleep(key);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }
                                                System.out.println("获取所有结果:" + key);
                                            }, threadPool))
                                    .toArray(CompletableFuture[]::new)
            );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    等待任何一个任务完成并返回

    CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(
                    list.stream().map(key ->
                            CompletableFuture.supplyAsync(() -> {
                                try {
                                    TimeUnit.SECONDS.sleep(key);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                return "获取单个结果:" + key;
                            }, threadPool)
                    ).toArray(CompletableFuture[]::new)
            );
            System.out.println(objectCompletableFuture.join());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    接力执行任务

    Integer join = CompletableFuture.supplyAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return 1;
                    }, threadPool)
                    .thenApplyAsync(result -> {
                        try {
                            TimeUnit.SECONDS.sleep(result);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return 2;
                    }, threadPool)
                    .join();
            System.out.println(join);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    常用API

    任务执行

    • supplyAsync:有返回值
    • runAsync:无返回值

    任务接力

    • thenRun thenRunAsync
    • thenAccept thenAcceptAsync
    • thenApply thenApplyAsync
    • handle handleAsync
    • applyToEither applyToEitherAsync
    • acceptEither acceptEitherAsync
    • runAfterEither runAfterEitherAsync
    • thenCombine thenCombineAsync
    • thenAcceptBoth thenAcceptBothAsync
      说明
    • 带run的方法,无入参,无返回值。
    • 带accept的方法,有入参,无返回值。
    • 带supply的方法,无入参,有返回值。
    • 带apply的方法,有入参,有返回值。
    • 带handle的方法,有入参,有返回值,并且带异常处理。
    • 以Async结尾的方法,都是异步的,否则是同步的。
    • 以Either结尾的方法,只需完成任意一个。
    • 以Both/Combine结尾的方法,必须所有都完成。

    任务结果获取

    • join 阻塞等待,不会抛异常
    • get 阻塞等待,会抛异常
    • complete(T value) 不阻塞,如果任务已完成,返回处理结果。如果没完成,则返回传参value。
    • completeExceptionally(Throwable ex) 不阻塞,如果任务已完成,返回处理结果。如果没完成,抛异常。

    转载自微信公众号-大侠学java

  • 相关阅读:
    Docker学习整理
    C++之Map与Set的模拟实现
    Spark3 AQE (Adaptive Query Execution) 一文搞懂 新特性
    .Net开源迁移框架FluentMigrator的使用。
    复现一次循环和两次循环
    AcWing 196. 质数距离
    华为机试真题 Java 实现【最长广播响应】
    dreamweaver网页大作业 我的家乡——南京玄武湖旅游攻略(4页) 学生网页设计作业源码
    [Android]Mac电脑Android Studio使用真机调试运行
    Win10电脑任务栏没有蓝牙图标的简单解决方法
  • 原文地址:https://blog.csdn.net/weixin_44504392/article/details/126585511