CompletableFuture 讲解系列
概述
关于 CompletableFuture,之前写过一篇《allOf 与 anyOf 的底层原理》。
这里再写一篇,介绍下其它 API 的使用,有必要时,说明下原理。
一、代码示例
比如,晚饭想吃鱼头豆腐汤,让老大去买鱼头,老二去买豆腐,
老妈在家,等东西都买回来了,就做鱼头豆腐汤。
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newCachedThreadPool();
Future<String> fishFuture = pool.submit(() -> getFish());
Future<String> tofuFuture = pool.submit(() -> getTofu());
String dinner = cookDinner(fishFuture.get(), tofuFuture.get());
}
private static String cookDinner(String fish, String tofu) {
String name = Thread.currentThread().getName();
System.out.println("当前线程名:" + name + ", 开始做晚餐啦!");
System.out.println(fish + "买到了," + tofu + "也买到了。");
return "鱼头豆腐汤";
}
private static String getTofu() {
String name = Thread.currentThread().getName();
System.out.println("当前线程名:" + name + ", 执行买豆腐任务");
return "钱大妈老豆腐";
}
这个普通版本,任务提交到线程池,用 Futrue 的 get 方法获取结果。
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newCachedThreadPool();
CompletableFuture<String> fishFuture = CompletableFuture.supplyAsync(() -> getFish(), pool);
String dinner = CompletableFuture.

本文详细介绍了Java中的CompletableFuture类,包括allOf方法的原理以及其它如supplyAsync、thenCombine等方法的使用和源码解析。文章通过实例展示了如何使用CompletableFuture进行异步任务处理,并通过链式编程合并任务。源码分析部分帮助理解其内部工作机制。
最低0.47元/天 解锁文章
169万+

被折叠的 条评论
为什么被折叠?



