completablefuture 的 thenrun 方法用于在当前任务完成时执行一个无输入、无输出的动作。它不会改变原 completablefuture 的结果,也不会接收前一步的计算结果,适合处理日志记录或状态清理等副作用操作。

如何确保 thenRun 在任务完成后执行
thenRun 会在其关联的前置 CompletableFuture 正常结束(包括成功返回或抛出异常)后自动触发。调用该方法会立即返回一个新的 CompletableFuture,该新实例仅用于等待动作执行完毕,不携带任何业务数据。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Result");
// 使用 thenRun 添加后置动作
CompletableFuture<Void> actionFuture = future.thenRun(() -> {
System.out.println("Action executed after completion");
});
// 获取原始结果并等待动作完成
String result = future.get();
actionFuture.get();
System.out.println(result);
}
}
thenRun 与 thenAccept 的区别是什么
两者的核心区别在于回调方法的参数和返回值。thenRun 接受 Runnable,没有参数也没有返回值;而 thenAccept 接受 Consumer<t></t>,可以接收上游任务的计算结果,但同样不返回新值。如果需要在后续步骤中使用上游结果,必须选择 thenAccept 或 thenApply。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
// thenRun: 无法访问上游结果
future.thenRun(() -> System.out.println("Done"));
// thenAccept: 可以访问上游结果
future.thenAccept(res -> System.out.println("Got: " + res));
}
}
前置任务抛出异常时 thenRun 还会执行吗
会执行。thenRun 的设计特性是无论前置任务是正常完成还是因异常终止,都会触发回调。这使其成为实现资源释放或统一日志记录的可靠手段,无需额外编写异常捕获逻辑。

















