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 小时前
【若依项目-产品经理视角】深度拆解 RuoYi-Vue-Pro 商城模块:从商品管理到交易引擎,50 张表撑起一整套电商系统码智社7 小时前
AES加密原理详解及Java实现加解密实战萧瑟余晖8 小时前
JDK 26 新特性详解马优晨9 小时前
Freemarker 完整讲解(后端 Java 模板引擎)维天说11 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态Zane199412 小时前
并发 vs 并行:别再傻傻分不清了,一文讲透 Java 并发编程的第一课噢,我明白了13 小时前
java中Excel的导入和导出(EasyExcel)吠品13 小时前
Zabbix Web界面误报Server未运行的排查与解决啊湘13 小时前
天气查询API接口 按月Token鉴权 实时天气 物联网可用 文档齐全Java内核笔记13 小时前
告别十亿美元的错误 : Spring Boot 4 空安全 (JSpecify) 实战