在 java 中,`completablefuture.runasync()` 用于提交一个无返回值、异步执行的任务。它接受一个 `runnable` 任务对象,并立即返回一个代表该任务执行结果的 `completablefuture

runAsync 与 supplyAsync 的核心区别是什么
两者的核心区别在于任务类型和返回值。`runAsync` 接收 `Runnable`,不产生返回值;`supplyAsync` 接收 `Supplier

import java.util.concurrent.CompletableFuture;
public class Demo {
public static void main(String[] args) {
// runAsync: 无返回值
CompletableFuture<Void> futureRun = CompletableFuture.runAsync(() -> {
System.out.println("Task running...");
});
// supplyAsync: 有返回值
CompletableFuture<String> futureSupply = CompletableFuture.supplyAsync(() -> {
return "Result";
});
}
}如何指定自定义线程池来运行任务
可以通过重载方法传入 `Executor` 参数来指定具体的线程池。如果不传,默认使用 `ForkJoinPool.commonPool()`。使用自定义线程池可以更好地控制资源隔离和并发度。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.*;
public class Demo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(4);
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running in custom pool");
}, pool);
pool.shutdown();
}
}runAsync 任务抛出异常时如何处理
如果 `runAsync` 中的任务抛出未捕获的异常,`CompletableFuture` 会处于异常完成状态。可以通过链式调用 `.exceptionally()` 或 `.handle()` 方法来处理这些异常,从而避免程序崩溃。

















