在 java 中,`thenaccept` 用于处理异步任务完成后的结果,它接收一个 `consumer` 函数式接口作为参数。该方法不会返回新的 `completablefuture`,而是直接消费上游任务的结果并执行副作用操作(如打印日志或更新状态)。调用时只需传入 lambda 表达式即可。

如何传递参数给 thenAccept
通过链式调用将上游任务的返回值传递给 `thenAccept`。例如,先启动一个异步计算,再使用 `thenAccept` 接收该计算结果。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<integer> future = CompletableFuture.supplyAsync(() -> {
return 42;
});
future.thenAccept(result -> {
System.out.println("Result: " + result);
});
// 等待异步任务完成
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}</integer>
如何处理异常
`thenAccept` 本身不处理异常,若上游抛出异常,下游不会执行。应结合 `exceptionally` 或 `handle` 处理错误情况。
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error");
}).exceptionally(e -> {
System.out.println("Exception: " + e.getMessage());
return null;
});
future.thenAccept(result -> {
if (result != null) {
System.out.println("Result: " + result);
}
});
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}</integer>
如何组合多个 thenAccept
可以连续调用 `thenAccept` 实现多步处理,但注意每个 `thenAccept` 都会阻塞后续步骤直到当前步骤完成。
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
return "Hello";
});
future.thenAccept(s -> {
System.out.println("Step 1: " + s);
}).thenAccept(s -> {
System.out.println("Step 2: " + s.toUpperCase());
});
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}</string>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










