代码对比
✕ Pre-Java 8
Future<String> future =
executor.submit(this::fetchData);
String data = future.get(); // blocks
String result = transform(data);
✓ Java 8+
CompletableFuture.supplyAsync(
this::fetchData
)
.thenApply(this::transform)
.thenAccept(IO::println);
发现此代码有问题? 告诉我们。
为什么现代方式更好
可链式调用
将异步步骤组合成可读的管道。
非阻塞
线程不会等待中间结果——只在需要时阻塞。
可组合
使用 thenCombine、allOf、anyOf 组合多个 Future。
旧方式
阻塞式 Future.get()
现代方式
CompletableFuture
自 JDK
8
难度
中级
JDK 支持
CompletableFuture 链式调用
可用
自 JDK 8 起广泛可用(2014 年 3 月)
工作原理
CompletableFuture 支持非阻塞异步管道。链式操作使用 thenApply、thenCompose 和 thenCombine,仅在最终结果需要时阻塞。
相关文档