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
相关推荐
人活一口气1 小时前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台像我这样帅的人丶你还3 小时前
Java 后端详解(三):全局异常处理与 JPA 数据库映射NE_STOP4 小时前
vibe Coding -- 小项目实战未秃头的程序猿9 小时前
Java 26正式发布!这3个新特性,让代码量直接减半用户2986985301410 小时前
Word 文档文本查找与替换的 Java 实现方案阿哉10 小时前
Nacos 服务发现源码:藏在背后的两套事件机制,90%的人只讲了一半咖啡八杯10 小时前
GoF设计模式——命令模式AI人工智能_电脑小能手10 小时前
【大白话说Java面试题 第125题】【并发篇】第25题:说说 Java 线程的中断机制Java内核笔记10 小时前
Spring Security 源码解析(六)无状态 JWT 实践:Session 共享与自定义过滤器荣码10 小时前
LangGraph多Agent协作:3个Agent干活比1个强,但我踩了4个坑