使用 thenaccept 消费 completablefuture 的结果,需要调用该实例的 thenaccept 方法并传入一个 consumer 函数式接口实现。该方法会异步执行回调逻辑,接收上游任务计算出的结果值,且自身不返回新值(返回 completablefuture),适合用于副作用操作如日志记录或数据保存。

thenAccept 与 thenApply 的核心区别是什么
thenAccept 专用于处理有返回值但无需转换结果的场景,其回调函数参数为上游任务的输出类型,返回类型为 void;而 thenApply 用于结果转换,回调函数接收输入并返回新类型的值。若误用 thenApply 却忽略返回值,会导致资源浪费;若需链式调用后续步骤,应确保前一步返回非空 CompletableFuture。

import java.util.concurrent.CompletableFuture;
public class Demo {
public static void main(String[] args) {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> "Hello");
// 使用 thenAccept 消费结果,无返回值
future.thenAccept(result -> System.out.println("Consumed: " + result));
// 等待主线程结束以便观察输出
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}</string>
thenAccept 如何处理异常中断流程
thenAccept 本身不捕获异常,若上游任务抛出异常,回调将不会执行,而是直接进入异常路径。此时应配合 exceptionally 或 handle 进行错误恢复。若需在消费结果的同时处理异常,建议使用 whenComplete,它无论成功与否都会执行回调,并提供结果和异常两个参数。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

import java.util.concurrent.CompletableFuture;
public class ErrorDemo {
public static void main(String[] args) {
CompletableFuture<string> failedFuture = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error occurred");
});
// thenAccept 不会执行,因为上游失败
failedFuture.thenAccept(res -> System.out.println("This won't print"));
// 使用 exceptionally 处理异常
failedFuture.exceptionally(ex -> {
System.err.println("Handled exception: " + ex.getMessage());
return "Fallback";
});
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}</string>
当 thenAccept 回调中发生未捕获异常时会怎样
若在 thenAccept 的回调函数内部抛出未捕获异常,该异常会被 CompletableFuture 框架捕获并封装为 CompletionException,导致当前 CompletableFuture 进入异常状态,后续依赖该阶段的 thenAccept、thenApply 等回调均不会执行。必须通过 exceptionally 或 handle 显式处理才能恢复流程。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










