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
相关推荐
嘻哈∠※6 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现白狐_7987 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序zander2587 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界码匠许师傅7 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值极创信息9 小时前
系统安全隐患全方位排查方案:标准化渗透测试全流程汉字萌萌哒10 小时前
2019CCF-CSP入门级C++试题解析喜欢的名字被抢了10 小时前
程序出问题怎么查,以及如何让它不掉线数据知道11 小时前
反序列化漏洞:Java、PHP、Python 三条线各讲透2601_9499506311 小时前
Java 面试准备,用练题簿把“背过八股”变成“真正会答”Rain的Java大神之路11 小时前
MQ重复消费问题怎么解决