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
相关推荐
许彰午8 小时前
14_Java泛型完全指南智慧物业老杨8 小时前
司法绿色通道下的物业纠纷数智化解决方案——基于“三优先“机制的全流程技术落地实践2601_961194028 小时前
2026初级会计实务公式总结大全|计算题公式手册PDF做个文艺程序员8 小时前
第1篇:K8s 核心概念精讲:Pod、Deployment、Service 与 Namespace——Java 开发者快速上手指南小欣加油10 小时前
leetcode3751 范围内总波动值I闪电悠米11 小时前
黑马点评-Redisson-01_why_redisson星轨zb11 小时前
LangChain4j 集成 Spring Boot:会话记忆 NPE 的根源与 ChatMemoryProvider 正确配置JAVA96511 小时前
JAVA面试-并发篇 05-并发包AQS队列实现原理是什么JAVA面经实录91711 小时前
RocketMQ全套学习知识手册phltxy11 小时前
Spring AI 从提示词到多模态