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
相关推荐
都叫我大帅哥15 分钟前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南Cao_Shixin攻城狮2 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理Dcs5 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!fouryears_234177 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别阿葱(聪)7 小时前
java 在k8s中的部署流程浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)板板正8 小时前
SpringAI——提示词(Prompt)、提示词模板(PromptTemplate)板板正8 小时前
SpringAI——对话记忆期待のcode8 小时前
图片上传实现李长渊哦9 小时前
深入理解Java中的Map.Entry接口