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
相关推荐
咖啡啡不加糖10 分钟前
RabbitMQ 消息队列:从入门到Spring Boot实战玩代码17 分钟前
Java线程池原理概述NE_STOP20 分钟前
SpringBoot--如何给项目添加配置属性及读取属性水果里面有苹果22 分钟前
20-C#构造函数--虚方法%d%d226 分钟前
python 在运行时没有加载修改后的版本金銀銅鐵32 分钟前
[Kotlin] 单例对象是如何实现的?泰勒疯狂展开33 分钟前
Java研学-MongoDB(三)zzywxc78739 分钟前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。张先shen1 小时前
Elasticsearch RESTful API入门:索引的增删改查完全指南天天摸鱼的java工程师1 小时前
工作八年,如果现在让我重做“教务系统”毕业设计,我会这样答...