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
相关推荐
kill bert1 小时前
Java八股文背诵 第四天JVM你是理想4 小时前
wait 和notify ,notifyAll,sleephelloworld工程师5 小时前
【微服务】SpringBoot整合LangChain4j 操作AI大模型实战详解Java&Develop5 小时前
idea里面不能运行 node 命令 cmd 里面可以运行咋回事啊q567315235 小时前
使用Java的HttpClient实现文件下载器你们补药再卷啦6 小时前
不用额外下载jar包,idea快速查看使用的组件源码爱的叹息6 小时前
Spring Boot 自定义配置类(包含字符串、数字、布尔、小数、集合、映射、嵌套对象)实现步骤及示例@西瓜@7 小时前
JAVAEE(多线程-线程池)returnShitBoy7 小时前
Go语言中的垃圾回收是如何工作的?有什么东东8 小时前
山东大学软件学院创新项目实训开发日志(9)之测试前后端连接