使用 completablefuture.runasync() 可以提交一个无返回值的任务,该任务会在异步线程池中执行。默认情况下,它使用公共的 forkjoinpool.commonpool(),你也可以传入自定义的 executor 来指定线程池。调用后立刻返回一个 completablefuture 对象,你可以用它来等待任务完成或处理异常。

runAsync 与 supplyAsync 的核心区别是什么
runAsync 接收的是 Runnable 接口,不产生返回值;而 supplyAsync 接收的是 Supplier 接口,会返回一个具体的值。如果你需要后续通过 thenApply 或 thenAccept 进行链式处理并获取结果,必须使用 supplyAsync。若只需执行副作用(如打印日志、写入数据库)而不关心结果,则 runAsync 更合适且语义更清晰。

一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RunAsyncDemo {
public static void main(String[] args) throws Exception {
// 1. 使用默认 ForkJoinPool
CompletableFuture<void> future1 = CompletableFuture.runAsync(() -> {
System.out.println("Task 1 running in: " + Thread.currentThread().getName());
});
// 2. 使用自定义线程池
ExecutorService customPool = Executors.newFixedThreadPool(2);
CompletableFuture<void> future2 = CompletableFuture.runAsync(() -> {
System.out.println("Task 2 running in: " + Thread.currentThread().getName());
}, customPool);
// 等待所有任务完成
CompletableFuture.allOf(future1, future2).join();
customPool.shutdown();
}
}</void></void>
如何捕获 runAsync 中抛出的异常
当 runAsync 中的 Runnable 抛出未捕获的异常时,这个异常会被封装在返回的 CompletableFuture 中。你可以通过 exceptionally 或 handle 方法来捕获并处理这些异常。如果不处理,调用 join() 时会抛出 CompletionException。建议在关键任务中使用 exceptionally 提供降级逻辑或记录错误日志。
import java.util.concurrent.CompletableFuture;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
CompletableFuture<void> future = CompletableFuture.runAsync(() -> {
if (true) throw new RuntimeException("Simulated Error");
}).exceptionally(ex -> {
System.err.println("Caught exception: " + ex.getMessage());
return null; // runAsync expects Void
});
try {
future.join(); // 如果没被 exceptionally 处理,这里会抛出 CompletionException
} catch (Exception e) {
System.err.println("Unhandled exception: " + e.getMessage());
}
}
}</void>
runAsync 在任务完成后如何通知主线程
虽然 runAsync 本身不返回值,但你可以通过 thenRun 或 thenAcceptBoth 等回调方法在主线程或其他线程中监听任务完成状态。例如,使用 thenRun 可以在任务结束后执行一段清理代码。此外,直接调用 join() 或 get() 是阻塞当前线程直到任务完成的经典方式,适用于需要同步结果的场景。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










