在 completionstage 的 runaftereither 中使用函数式接口,需要传入一个实现了 consumer super t> 接口的对象。由于 runaftereither 是“运行后”操作,它不产生新的值,因此只能接受无返回值的消费型逻辑。你可以通过 lambda 表达式或方法引用直接提供这个消费者,当两个阶段中任意一个完成时,该逻辑就会被执行。

如何为 runAfterEither 编写 Consumer 逻辑
要使用 Consumer,只需关注输入参数的处理。因为 runAfterEither 会在任一阶段完成后触发,所以传入的 Consumer 会接收到那个已完成阶段的结果。如果只需要执行副作用(如打印日志),可以直接忽略参数;如果需要处理结果,则将其作为参数接收。这种用法适用于不需要链式调用后续异步任务的场景。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<string> stage1 = CompletableFuture.supplyAsync(() -> "Result 1");
CompletableFuture<string> stage2 = CompletableFuture.supplyAsync(() -> "Result 2");
// 使用 runAfterEither,传入 Consumer
stage1.runAfterEither(stage2, result -> {
System.out.println("Completed with: " + result);
});
// 等待主线程结束以观察输出
Thread.sleep(1000);
}
}</string></string>
runAfterEither 与 thenAcceptEither 的区别是什么
两者的核心区别在于返回值类型和后续处理能力。runAfterEither 返回的是 CompletableFuture,意味着它不产生新值,无法继续链式调用其他数据转换操作。而 thenAcceptEither 同样接受 Consumer,但它返回的是原始的 CompletionStage 类型,允许你在消费完结果后继续链接其他阶段。选择 runAfterEither 仅当你确定该分支是终点且无需进一步处理时使用。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<integer> futureA = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<integer> futureB = CompletableFuture.supplyAsync(() -> 20);
// runAfterEither: 返回 CompletableFuture<void>,不可链式调用
futureA.runAfterEither(futureB, res -> System.out.println("Run: " + res));
// thenAcceptEither: 返回 CompletableFuture<integer>,可链式调用
futureA.thenAcceptEither(futureB, res -> System.out.println("Then: " + res))
.thenApply(res -> res * 2); // 可以继续处理
}
}</integer></void></integer></integer>
如果两个阶段都抛出异常,Consumer 会收到什么
当两个阶段都抛出异常时,runAfterEither 中的 Consumer **不会**被调用。因为 runAfterEither 依赖于至少有一个阶段正常完成(completed normally)才能触发回调。如果两个阶段都以异常结束,没有任何阶段提供结果,那么该回调将被跳过。此时,只有监听这两个阶段的 exceptionally 或 handle 回调会被触发。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










