答案:Java中通过CompletableFuture实现异步任务组合,支持串行(thenApply、thenCompose、thenAccept)、并行(allOf、anyOf)、结果合并(thenCombine)及异常处理(exceptionally、handle),可有效构建高效、响应性强的异步流程。
在Java中组合异步任务,主要依赖 CompletableFuture 类。它提供了丰富的API来编排多个异步操作,支持串行执行、并行执行、合并结果、异常处理等场景。合理使用这些方法可以提升程序响应性和资源利用率。
当某个异步任务依赖前一个任务的结果时,使用 thenApply、thenCompose 或 thenAccept 进行串行组合。
示例:
CompletableFuture
future = CompletableFuture .supplyAsync(() -> "Hello") .thenApply(s -> s + " World") .thenApply(String::toUpperCase); future.thenAccept(System.out::println); // 输出: HELLO WORLD
多个独立异步任务可并行执行,通过 allOf 或 anyOf 组合管理生命周期。
示例:
CompletableFuturef1 = CompletableFuture.supplyAsync(() -> { sleep(1000); return "Task 1"; }); CompletableFuture f2 = CompletableFuture.supplyAsync(() -> { sleep(500); return "Task 2"; }); CompletableFuture allDone = CompletableFuture.allOf(f1, f2); allDone.thenRun(() -> { System.out.println("Both tasks finished."); System.out.println("f1 result: " + f1.join()); System.out.println("f2 result: " + f2.join()); });
使用 thenCombine 将两个异步任务的结果合并为一个新值。
该方法适用于需要聚合多个异步查询结果的场景,比如从不同服务获取用户信息和订单信息后合并展示。
CompletableFuturepriceFuture = CompletableFuture.supplyAsync(() -> fetchPrice()); CompletableFuture taxFuture = CompletableFuture.supplyAsync(() -> fetchTax()); CompletableFuture totalFuture = priceFuture.thenCombine(taxFuture, (price, tax) -> price + tax); totalFuture.thenAccept(total -> System.out.println("Total: " + total));
异步任务出错不会立即抛出异常,需通过 exceptionally 或 handle 显式处理。
示例:
CompletableFutureriskyFuture = CompletableFuture .supplyAsync(() -> { if (Math.random() < 0.5) throw new RuntimeException("Fail"); return "Success"; }) .exceptionally(ex -> "Fallback due to " + ex.getMessage()); riskyFuture.thenAccept(System.out::println);
基本上就这些。掌握这些组合方式后,就能灵活构建复杂的异步流程,而不陷入回调地狱。关键是理解每个组合方法的行为差异,并根据依赖关系选择合适的方式。不复杂但容易忽略的是异常传播和结果收集细节,务必测试完整路径。