Java中如何用CompletableFuture组合异步操作
completablefuture的常用组合方法包括thencombine、thencompose、allof、thenapply、thenaccept、anyof和ortimeout。其中thencombine用于合并两个独立future的结果,thencompose用于将一个future的结果作为另一个future的输入,allof用于等待多个future完成,thenapply允许对一个future的结果进行转换,thenaccept允许对结果执行操作但不返回值,anyof允许等待多个future中的任何一个完成,ortimeout用于设置超时时间。此外,处理异常的方法包括exceptionally提供默认值或恢复逻辑,handle用于同时处理正常结果和异常情况,并且相较于传统future,completablefuture具有非阻塞性、丰富的组合能力、异常处理机制及支持超时控制等优势,显著提升了异步编程的灵活性和健壮性。
使用CompletableFuture组合异步操作,核心在于将多个独立的异步任务串联或并行执行,最终得到一个整合的结果。这能显著提升程序的并发性和响应速度,尤其是在处理I/O密集型任务时。

import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureExample { public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return "Error in Future 1"; } return "Result from Future 1"; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { // 模拟另一个耗时操作 try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return "Error in Future 2"; } return "Result from Future 2"; }); // 使用 thenCombine 组合两个 Future 的结果 CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> { return result1 + " and " + result2; }); // 获取组合后的结果 String finalResult = combinedFuture.get(); System.out.println("Combined Result: " + finalResult); // 使用 thenCompose 链接 Future CompletableFuture<String> composedFuture = future1.thenCompose(result1 -> { return CompletableFuture.supplyAsync(() -> { return result1 + " processed further"; }); }); String composedResult = composedFuture.get(); System.out.println("Composed Result: " + composedResult); // 使用 allOf 等待所有 Future 完成 CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2); allFutures.get(); // 等待所有 future 完成 System.out.println("All futures completed"); // 处理异常 CompletableFuture<String> futureWithError = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Simulated error"); }).exceptionally(ex -> { System.err.println("Caught exception: " + ex.getMessage()); return "Recovered from error"; }); String errorResult = futureWithError.get(); System.out.println("Error Result: " + errorResult); } }
文章标题:Java中如何用CompletableFuture组合异步操作
文章链接:https://onehaoka.com/6029.html
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明来自磁力搜索 !
Java中如何比较日期 详解Java日期比较的三种方式
在java中比较日期的三种常见方法为:1. 使用date.compareto()方法进行简单直接的日期比较;2. 使用calendar.compareto()
2025年06月23日
Java中如何用CompletableFuture组合异步操作
completablefuture的常用组合方法包括thencombine、thencompose、allof、thenapply、thenaccept、an
2025年06月23日
惠普暗影精灵主机风扇不转?温控、硬件老化故障排查
惠普暗影精灵主机风扇不转的主要原因包括灰尘堆积、温控策略设置、风扇或主板故障等。1.首先应断电清理灰尘,检查风扇是否卡滞;2.尝试手动拨动风扇叶片,若阻力大则
2025年06月23日
Excel表格中如何合并不同条件的筛选数据 动态整合
要动态整合excel表格中不同条件筛选的数据,核心方法包括使用高级筛选和公式、vba宏、power query及辅助列+公式。1. 高级筛选和公式:设置条件区
2025年06月23日
pytest如何统计异常处理分支的测试覆盖率?哪些插件可增强检查?
pytest默认不统计try...except中except分支的覆盖率,需额外配置。1. 安装pytest和pytest-cov;2. 使用--cov-br
2025年06月23日
Java中HashMap的解析_Java中HashMap的详细使用
hashmap是java中一种存储键值对的数据结构,其底层由数组+链表(或红黑树)组成;1.通过哈希函数将键转换为数组索引以实现快速存取;2.采用链地址法解决
2025年06月23日
Golang中大数据量排序性能差怎么优化
优化golang大数据量排序性能需综合考虑算法选择、内存使用和并发处理。1.选择合适的排序算法,如快速排序适合数据分布未知场景,归并排序适合稳定排序需求,堆排
2025年06月23日
《罪恶装备》开发商将在本周五正式揭晓全新作
arc system works宣布将于本周五举行一场网络直播发布会,正式揭晓其全新作品。 这家总部位于日本横滨的游戏开发兼发行商表示,直播活动将在北京时间
2025年06月23日
最新评论