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

在Java中使用CompletableFuture组合多个异步任务,可以高效地处理并行操作、依赖关系和结果聚合。通过合理利用其提供的API,能写出简洁且高性能的异步代码。
当多个任务彼此独立,你想等它们全部完成后再进行下一步,可以使用 CompletableFuture.allOf。
说明: allOf 接收多个 CompletableFuture 实例,返回一个新的 Future,它在所有任务都完成后才完成。
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
sleep(1000);
return "Result1";
});
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
sleep(800);
return "Result2";
});
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
sleep(1200);
return "Result3";
});
// 等待所有任务完成
CompletableFuture<Void> 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);
}
});
如果一个任务依赖前一个任务的结果,可以用 thenApply 或 thenCompose 实现链式调用。
立即学习“Java免费学习笔记(深入)”;
thenApply:适用于同步转换前一个任务的结果。thenCompose:用于将前一个结果映射为另一个 CompletableFuture(扁平化嵌套 Future)。CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World") // 同步处理
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "!")); // 异步继续
future.thenAccept(System.out::println); // 输出: Hello World!
当你有两个异步任务,并希望在两者都完成后合并它们的结果,使用 thenCombine。
CompletableFuture<Integer> priceFuture = CompletableFuture.supplyAsync(() -> getPrice());
CompletableFuture<Integer> taxFuture = CompletableFuture.supplyAsync(() -> getTax());
CompletableFuture<Integer> totalFuture = priceFuture.thenCombine(taxFuture, (price, tax) -> price + tax);
totalFuture.thenAccept(total -> System.out.println("Total: " + total));
如果你只需要多个任务中任意一个完成即可响应,比如超时或降级逻辑,可用 CompletableFuture.anyOf。
注意: anyOf 返回 CompletableFuture<Object>,需要手动转型。
CompletableFuture<String> fast = CompletableFuture.supplyAsync(() -> {
sleep(500);
return "Fast result";
});
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
sleep(2000);
return "Slow result";
});
CompletableFuture<Object> anyDone = CompletableFuture.anyOf(fast, slow);
anyDone.thenAccept(result -> System.out.println("First done: " + result)); // 打印 Fast result
基本上就这些常用模式。根据任务之间的关系选择合适的方法:并行用 allOf,串行用 thenApply 或 thenCompose,合并结果用 thenCombine,抢答场景用 anyOf。不复杂但容易忽略的是异常处理和线程池配置,建议生产环境指定自定义线程池避免阻塞ForkJoinPool。
以上就是在Java中如何组合CompletableFuture多任务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号