使用CompletableFuture可高效组合异步任务:1. allOf并行执行多个独立任务,等待全部完成;2. thenApply/thenCompose实现串行依赖任务,后者用于扁平化嵌套Future;3. thenCombine合并两个任务结果;4. anyOf响应首个完成任务,适用于抢答或超时场景。需注意异常处理与自定义线程池配置以避免阻塞默认线程池。

在Java中使用CompletableFuture组合多个异步任务,可以高效地处理并行操作、依赖关系和结果聚合。通过合理利用其提供的API,能写出简洁且高性能的异步代码。
1. 并行执行多个独立任务(allOf)
当多个任务彼此独立,你想等它们全部完成后再进行下一步,可以使用 CompletableFuture.allOf。
说明: allOf 接收多个 CompletableFuture 实例,返回一个新的 Future,它在所有任务都完成后才完成。
CompletableFuturetask1 = CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 sleep(1000); return "Result1"; }); CompletableFuture task2 = CompletableFuture.supplyAsync(() -> { sleep(800); return "Result2"; }); CompletableFuture task3 = CompletableFuture.supplyAsync(() -> { sleep(1200); return "Result3"; }); // 等待所有任务完成 CompletableFuture allDone = CompletableFuture.allOf(task1, task2, task3); // 获取结果(注意:allOf 返回 Void,需手动提取) allDone.thenRun(() -> { try { System.out.println("All done: " + task1.get() + ", " + task2.get() + ", " + task3.get()); } catch (Exception e) { throw new RuntimeException(e); } });
2. 串行执行有依赖的任务(thenApply / thenCompose)
如果一个任务依赖前一个任务的结果,可以用 thenApply 或 thenCompose 实现链式调用。
立即学习“Java免费学习笔记(深入)”;
由于疫情等原因大家都开始习惯了通过互联网上租车服务的信息多方面,且获取方式简便,不管是婚庆用车、旅游租车、还是短租等租车业务。越来越多租车企业都开始主动把租车业务推向给潜在需求客户,所以如何设计一个租车网站,以便在同行中脱颖而出就重要了,易优cms针对租车行业市场需求、目标客户、盈利模式等,进行策划、设计、制作,建设一个符合用户与搜索引擎需求的租车网站源码。 网站首页
-
thenApply:适用于同步转换前一个任务的结果。 -
thenCompose:用于将前一个结果映射为另一个 CompletableFuture(扁平化嵌套 Future)。
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "Hello") .thenApply(s -> s + " World") // 同步处理 .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "!")); // 异步继续 future.thenAccept(System.out::println); // 输出: Hello World!
3. 合并两个任务的结果(thenCombine)
当你有两个异步任务,并希望在两者都完成后合并它们的结果,使用 thenCombine。
CompletableFuturepriceFuture = CompletableFuture.supplyAsync(() -> getPrice()); CompletableFuture taxFuture = CompletableFuture.supplyAsync(() -> getTax()); CompletableFuture totalFuture = priceFuture.thenCombine(taxFuture, (price, tax) -> price + tax); totalFuture.thenAccept(total -> System.out.println("Total: " + total));
4. 处理任意任务先完成(anyOf)
如果你只需要多个任务中任意一个完成即可响应,比如超时或降级逻辑,可用 CompletableFuture.anyOf。
注意: anyOf 返回 CompletableFuture,需要手动转型。
CompletableFuturefast = CompletableFuture.supplyAsync(() -> { sleep(500); return "Fast result"; }); CompletableFuture slow = CompletableFuture.supplyAsync(() -> { sleep(2000); return "Slow result"; }); CompletableFuture
基本上就这些常用模式。根据任务之间的关系选择合适的方法:并行用 allOf,串行用 thenApply 或 thenCompose,合并结果用 thenCombine,抢答场景用 anyOf。不复杂但容易忽略的是异常处理和线程池配置,建议生产环境指定自定义线程池避免阻塞ForkJoinPool。









