在 java 中,使用 completablefuture 的 supplyasync 方法可以异步执行一个返回值的任务。具体做法是调用 completablefuture.supplyasync() 并传入一个实现 supplier<t></t> 接口的 lambda 表达式或函数式接口实例,该方法会立即提交任务到线程池并返回一个代表未来结果的 completablefuture 对象,你可以通过 .get() 阻塞获取结果或使用 .thenapply() 链式处理后续逻辑。

supplyAsync 默认使用哪个线程池?
如果不指定 Executor,supplyAsync 默认使用公共的 ForkJoinPool.commonPool()。这个线程池的大小由 JVM 属性 java.util.concurrent.ForkJoinPool.common.parallelism 决定,通常等于 CPU 核心数减一。这意味着如果你的任务是 CPU 密集型且数量较多,可能会与其他共享该池的任务产生竞争;如果是 I/O 密集型任务,建议使用自定义线程池以避免线程耗尽。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SupplyAsyncDemo {
public static void main(String[] args) throws Exception {
// 1. 使用默认 ForkJoinPool
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
return "Default Pool: " + Thread.currentThread().getName();
});
// 2. 使用自定义线程池
ExecutorService customPool = Executors.newFixedThreadPool(2);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
return "Custom Pool: " + Thread.currentThread().getName();
}, customPool);
System.out.println(future1.get());
System.out.println(future2.get());
customPool.shutdown();
}
}
如何对 supplyAsync 的结果进行链式处理?
可以通过 thenApply、thenAccept 或 exceptionally 等方法对 supplyAsync 返回的 CompletableFuture 进行链式操作。例如,使用 thenApply 可以将异步任务的返回值转换为另一种类型,而 exceptionally 则用于处理异步执行过程中抛出的异常。这些方法都会返回一个新的 CompletableFuture,支持无限链式调用,直到最终通过 get() 或 join() 获取最终结果。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ChainProcessingDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int num = 10;
if (num == 0) throw new RuntimeException("Zero error");
return num;
})
.thenApply(result -> result * 2)
.thenApply(result -> result + 5)
.exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return -1;
});
System.out.println("Result: " + future.get());
}
}
当 supplyAsync 抛出异常时,get() 会返回什么?
如果 supplyAsync 中的任务抛出未捕获的异常,get() 方法不会直接返回正常值,而是抛出 ExecutionException。你需要通过 getCause() 获取原始异常。为了避免手动处理 ExecutionException,推荐使用 exceptionally 或 handle 方法进行优雅的错误处理,这样可以在不中断链式调用的前提下提供默认值或日志记录。


















