当前位置: 首页 > news >正文

CompletableFuture到底怎么用?

CompletableFuture 提供了强大的功能来处理异步编程任务。CompletableFuture它同时实现了FutureCompletionStage两个接口。

创建异步任务

  1. CompletableFuture.supplyAsync(),支持返回值。
  2. CompletableFuture.runAsync(),不支持返回值。
// 可以自定义线程池
ExecutorService executor = Executors.newCachedThreadPool();
// runAsync的使用
CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() -> System.out.println("run,关注公众号:捡田螺的小男孩"), executor);
// supplyAsync的使用
CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {System.out.print("supply,关注公众号:捡田螺的小男孩");return "捡田螺的小男孩"; }, executor);

获取返回结果

  1. CompletableFuture.join(),如果异步操作尚未完成,get() 方法会阻塞当前线程直到操作完成。join() 不会抛出 InterruptedException。如果当前线程在等待期间被中断,join() 会将中断状态设置回线程,但不抛出异常。
  2. CompletableFuture.get(),如果异步操作尚未完成,get() 方法会阻塞当前线程直到操作完成。如果异步操作失败,get() 方法会抛出 ExecutionException 来包装原始的异常。
// runAsync的future没有返回值,输出null
System.out.println(runFuture.join());
// supplyAsync的future,有返回值
System.out.println(supplyFuture.join());

异步任务的回调

  1. CompletableFuture.thenRun/thenRunAsync(),在异步操作完成后同步/异步执行一个无入参、无返回值的操作。
CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(()->{System.out.println("先执行第一个CompletableFuture方法任务");return "捡田螺的小男孩";}
);CompletableFuture thenRunFuture = orgFuture.thenRun(() -> {System.out.println("接着执行第二个任务");
});
  1. CompletableFuture.thenAccept/thenApplyAsync(),在异步操作完成后同步/异步执行一个有入参、有返回值的操作。
CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(()->{System.out.println("原始CompletableFuture方法任务");return "捡田螺的小男孩";}
);CompletableFuture<String> thenApplyFuture = orgFuture.thenApply((a) -> {if ("捡田螺的小男孩".equals(a)) {return "关注了";}return "先考虑考虑";
});
  1. CompletableFuture.exceptionally(),用于处理异步操作中的异常。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {if (Math.random() > 0.5) {throw new RuntimeException("Operation failed!");}return 42;
}).exceptionally(throwable -> {// 异常处理逻辑System.out.println("Handling exception: " + throwable.getMessage());// 返回一个替代的结果return -1;
});System.out.println("Future result: " + future.join()); // 如果有异常,输出将是 -1

异步任务的组合操作

  1. CompletableFuture.thenCombine/thenCombineAsync(),用于将两个异步操作的结果组合起来。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + ", " + s2);
System.out.println(combinedFuture.join()); // 输出 "Hello, World"
  1. CompletableFuture.thenCompose/thenComposeAsync(),用于在异步操作完成后,将结果传递给另一个异步操作。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
System.out.println(future.join());
  1. CompletableFuture.allOf(),等待多个 CompletableFuture 都完成。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "!");CompletableFuture<Void> allFuture = CompletableFuture.allOf(future1, future2, future3);
allFuture.thenRun(() -> System.out.println("Both futures are complete."));
  1. CompletableFuture.anyOf(),等待多个 CompletableFuture 任意一个完成。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "!");CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2, future3);
anyFuture.thenAccept(completedFuture -> System.out.println("One of the futures is complete."));
http://www.xdnf.cn/news/126559.html

相关文章:

  • Code Splitting 分包策略
  • MobTech袤博ShareSDK集成错误 ld: symbol(s) not found for architecture arm64
  • 《一文读懂Transformers库:开启自然语言处理新世界的大门》
  • 【重走C++学习之路】18、map和set
  • 基于RFID的智能家居系统设计与实现
  • Spring—依赖注入注解
  • 从认证到透传:用 Nginx 为 EasySearch 构建一体化认证网关
  • 【Java 8新特性】Stream API 和 Lambda 表达式
  • MySQL数据库基本操作-DQL-基本查询
  • 多线程事务?拿捏!
  • 豆包桌面版 1.47.4 可做浏览器,免安装绿色版
  • [创业之路-382]:企业法务 - 企业如何通过技术专利与技术秘密保护自己
  • AI赋能Python长时序植被遥感动态分析、物候提取、时空变异归因及RSEI生态评估
  • WebServiceg工具
  • 虾皮(Shopee)商品详情 API 接口概述及 JSON 数据返回参考
  • 《Pinia 从入门到精通》Vue 3 官方状态管理 -- 基础入门篇
  • inih介绍
  • Fragment控件
  • Pytest安装
  • CVPR2025W | S-EO 遥感几何感知阴影检测大规模数据集, 将开源
  • 电商指标体系搭建 - AxureMost
  • Java虚拟机(JVM)家族发展史及版本对比
  • 利用 SSE 实现文字吐字效果:技术与实践
  • 【含文档+PPT+源码】基于SpringBoot+Vue的移动台账管理系统
  • 车载客流记录仪简介
  • 深入解析:`[‘1‘, ‘0‘][101 % 2]` 这种写法在不同编程语言中的实现与应用
  • 交换式以太网
  • 自然语言处理(NLP)技术的实例
  • 函数模板 (Function Templates)
  • OSPF动态路由(单臂路由)