ExecutorService executor = new ThreadPoolExecutor(
8, 16, 60,
TimeUnit.MINUTES,
new ArrayBlockingQueue<>(100)
);
Random random=new Random(10);
//模拟查询用户列表
List<User> list=selectUsers();//需要执行的任务列表
// 任务列表
List<CompletableFuture<User>> fList = new ArrayList<>();
list.forEach(u->{
CompletableFuture<User> f = CompletableFuture.supplyAsync(//异步执行方法
//执行耗时较长的业务代码,这里模拟一下
()->{
//执行完成,设置返回结果 设置 coede 和 list
u.setAge(random.nextInt(100));
u.setName(UUID.randomUUID().toString());
return u;
},
executor
);
fList.add(f);
});
// 阻塞,等待所有任务执行完成
CompletableFuture<Void> all= CompletableFuture.allOf(fList.toArray(new CompletableFuture[0]));
//因为allOf没有返回值,所以需要通过thenApply回调函数获取结果
CompletableFuture<List<User>> allUser=all.thenApply(v-> fList.stream().map(a-> {
try {
return a.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList()));
// ---------------获取返回值-----------------
try {
list=allUser.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
CompletableFuture 异步调用,获取返回值
Cyclic10012023-11-03 9:51
相关推荐
alonewolf_9919 小时前
JDK17新特性全面解析:从语法革新到模块化革命一嘴一个橘子19 小时前
spring-aop 的 基础使用(啥是增强类、切点、切面)- 2sheji341619 小时前
【开题答辩全过程】以 中医药文化科普系统为例,包含答辩的问题和答案恋爱绝缘体119 小时前
2020重学C++重构你的C++知识体系wszy180920 小时前
新文章标签:让用户一眼发现最新内容wszy180920 小时前
顶部标题栏的设计与实现:让用户知道自己在哪程序员小假21 小时前
我们来说一下无锁队列 Disruptor 的原理资生算法程序员_畅想家_剑魔21 小时前
Kotlin常见技术分享-02-相对于Java 的核心优势-协程ProgramHan21 小时前
Spring Boot 3.2 新特性:虚拟线程的落地实践nbsaas-boot1 天前
Go vs Java 的三阶段切换路线图