1. 从Future到CompletableFuture:Java异步编程的进化史
2004年Java 5引入的Future接口,就像去餐厅吃饭时拿到的一张取餐小票——你点完餐后可以继续做其他事情,等餐好了再凭票取餐。但这种模式存在明显缺陷:你无法知道餐点何时准备好,必须不断主动询问"我的菜好了吗?"。
java复制ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
Thread.sleep(2000); // 模拟耗时操作
return "处理结果";
});
// 阻塞式获取结果
String result = future.get(); // 厨师没做完你就只能干等着
CompletableFuture在Java 8的诞生,相当于给餐厅装上了智能叫号系统。它通过回调机制主动通知你:"您的餐点已准备好,请到3号窗口取餐"。这种范式转换带来了真正的异步编程体验。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. CompletableFuture核心机制解析
2.1 双接口实现的设计哲学
CompletableFuture同时实现了Future和CompletionStage接口,这种双继承设计体现了其"承前启后"的定位:
- Future接口保障了对历史代码的兼容性
- CompletionStage接口定义了40余个流式操作方法,支持函数式编程
java复制public class CompletableFuture<T>
implements Future<T>, CompletionStage<T> {
// 实现细节...
}
2.2 任务编排的乐高积木模型
CompletableFuture最强大的能力在于任务编排,就像用乐高积木搭建复杂结构。以下是几种典型模式:
- 串行流水线(thenApply):
java复制CompletableFuture.supplyAsync(() -> "hello")
.thenApply(s -> s + " world")
.thenAccept(System.out::println); // 输出"hello world"
- 并行聚合(thenCombine):
java复制CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
future1.thenCombine(future2, (x, y) -> x + y)
.thenAccept(sum -> System.out.println("总和: " + sum));
- 竞速模式(anyOf):
java复制CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return "结果A";
});
CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> "结果B");
CompletableFuture.anyOf(futureA, futureB)
.thenAc
