17370845950

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

在Java中使用CompletableFuture组合多个异步任务,可以高效地处理并行操作、依赖关系和结果聚合。通过合理利用其提供的API,能写出简洁且高性能的异步代码。

1. 并行执行多个独立任务(allOf)

当多个任务彼此独立,你想等它们全部完成后再进行下一步,可以使用 CompletableFuture.allOf

说明: allOf 接收多个 CompletableFuture 实例,返回一个新的 Future,它在所有任务都完成后才完成。

示例:
CompletableFuture task1 = 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)

如果一个任务依赖前一个任务的结果,可以用 thenApplythenCompose 实现链式调用。

  • thenApply:适用于同步转换前一个任务的结果。
  • thenCompose:用于将前一个结果映射为另一个 CompletableFuture(扁平化嵌套 Future)。
示例:
CompletableFuture future = CompletableFuture
    .supplyAsync(() -> "Hello")
    .thenApply(s -> s + " World")           // 同步处理
    .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "!")); // 异步继续

future.thenAccept(System.out::println); // 输出: Hello World!

3. 合并两个任务的结果(thenCombine)

当你有两个异步任务,并希望在两者都完成后合并它们的结果,使用 thenCombine

示例:
CompletableFuture priceFuture = 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,需要手动转型。

示例:
CompletableFuture fast = CompletableFuture.supplyAsync(() -> {
    sleep(500);
    return "Fast result";
});

CompletableFuture slow = CompletableFuture.supplyAsync(() -> {
    sleep(2000);
    return "Slow result";
});

CompletableFuture anyDone = CompletableFuture.anyOf(fast, slow);

anyDone.thenAccept(result -> System.out.println("First done: " + result)); // 打印 Fast result


基本上就这些常用模式。根据任务之间的关系选择合适的方法:并行用 allOf,串行用 thenApplythenCompose,合并结果用 thenCombine,抢答场景用 anyOf。不复杂但容易忽略的是异常处理和线程池配置,建议生产环境指定自定义线程池避免阻塞ForkJoinPool。