使用 thenapply、thenaccept 或 thencompose 等串行方法,将前一个 completablefuture 的完成动作作为后一个任务的触发条件,即可保证依赖顺序。这些方法会返回一个新的 completablefuture,该任务仅在原任务成功完成后才执行,从而形成一条线性的执行链。

thenApply 如何转换数据并传递结果
thenApply 用于在前一个任务完成后,对其结果进行转换并返回新值。它接收一个 Function 接口,输入是上一个任务的返回值,输出是新任务的返回值。这种方式适合处理纯计算逻辑,且需要保留中间结果供后续使用的场景。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> step1 = CompletableFuture.supplyAsync(() -> "Hello");
// thenApply 接收上一步的结果 "Hello",转换为大写
CompletableFuture<String> step2 = step1.thenApply(s -> s.toUpperCase());
// 获取最终结果
System.out.println(step2.get()); // 输出: HELLO
}
}运行上述代码,控制台将输出 HELLO。这证明了 step2 确实等待 step1 完成后才执行,并且正确接收了 step1 的返回值。
立即学习“Java免费学习笔记(深入)”;
一个围绕官方 Mailgun JavaScript SDK 构建的 ASE 技能,用于从 Node.js 发送电子邮件和管理 Mailgun API 工作流。它适用于需要事务性消息传递、域名感知电子邮件操作、事件处理以及与 Mailgun 平台直接集成的代理任务。
thenAccept 如何处理副作用而不改变结果
thenAccept 用于在前一个任务完成后,执行一个带有副作用的操作(如打印日志、保存数据库),但不产生新的返回值。它接收一个 Consumer 接口,输入是上一个任务的返回值。该方法返回的是 CompletableFuture<void></void>,意味着它不向链条下游传递任何有效数据。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> step1 = CompletableFuture.supplyAsync(() -> 42);
// thenAccept 接收上一步的结果 42,执行打印操作
CompletableFuture<Void> step2 = step1.thenAccept(result -> {
System.out.println("Received: " + result);
});
// 等待 step2 完成
step2.get();
}
}运行上述代码,控制台将输出 Received: 42。这表明 thenAccept 成功捕获了上游任务的结果并执行了指定操作,同时没有干扰主流程的数据流。
当 thenCompose 遇到嵌套 Future 时如何扁平化
thenCompose 专门用于处理前一个任务返回另一个 CompletableFuture 的情况。它将两个异步操作“扁平化”为一个单一的 CompletableFuture,避免了手动调用 .get() 导致的阻塞。这是实现真正非阻塞串行的关键方法。
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<CompletableFuture<String>> nestedFuture =
CompletableFuture.supplyAsync(() -> "Inner")
.thenApply(inner -> CompletableFuture.supplyAsync(() -> inner + " World"));
// 使用 thenCompose 扁平化
CompletableFuture<String> flatFuture =
CompletableFuture.supplyAsync(() -> "Start")
.thenCompose(start ->
CompletableFuture.supplyAsync(() -> start + " Middle")
.thenApply(mid -> mid + " End")
);
System.out.println(flatFuture.get()); // 输出: Start Middle End
}
}运行上述代码,控制台将输出 Start Middle End。thenCompose 确保了内部 CompletableFuture 在外部任务完成后才启动,实现了严格的串行依赖,且全程无阻塞。

















