CompletableFuture.allOf that doens't return Void(CompletableFuture.allOf不能返回Void的解决方法)
2024-09-03 11:09:13
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream; public class Main { static CompletableFuture<List<?>> allOf(CompletableFuture<?>... cfs) {
return CompletableFuture.allOf(cfs)
.thenApply(ignore -> Stream.of(cfs)
.map(cf -> cf.join())
.collect(Collectors.toList()));
} public static void main(String[] args) { // we have 3 (or any number) of CompletableFutures
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {sleep(); return "HELLO";});
CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {sleep(); return ;});
CompletableFuture<Double> cf3 = CompletableFuture.supplyAsync(() -> {sleep(); return 20d;}); CompletableFuture<List<?>> allOf = allOf(cf1, cf2, cf3); //we call the method we just created above // we can get the -already there - result either using then
// Get result using:
allOf.thenAccept(l -> l.forEach(System.out::println)); // or using CompletableFuture.join() (or CompletableFuture.get())
// OR (non-typesafe)
String s = (String) allOf.join().get();
Integer i = (Integer) allOf.join().get();
Double d = (Double) allOf.join().get();
System.out.println(s + ", " + i + ", "+ d); sleep(); // because default CompletableFuture Executor is a daemon-thread based executor
} private static void sleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
摘录地址:http://m-hewedy.blogspot.com/2017/02/completablefutureallof-that-doenst.html
最新文章
- 如何将已部署在ASM的资源迁移到ARM中
- ORA-12537: TNS:connection closed
- 关于onethink的迁移站点产生数据库错误
- 密码学初级教程(六)数字签名 Digital Signature
- 新一代IDE Light Table开源:让编程工作更简单
- 【转载】Linux动态库搜索路径的技巧
- footable动态载入数据
- 框架学习笔记:Unity3D的MVC框架——StrangeIoC
- PCB布线的地线干扰与抑制方法
- ADS-B 雷达 显示终端5.8
- 浅谈Swift和OC的区别
- PE文件详解(五)
- botzone Tetris2
- ELK+filebeat、kafka、zookeeper搭建文档
- ajax处理跨域有几种方式
- 理解WebKit和Chromium: Chromium插件和扩展基础
- TrieTree
- vsftpd.configro
- nginx 禁止恶意域名解析
- C++学习基础十七-- 函数指针
热门文章
- [ZOJ 3610] Yet Another Story of Rock-paper-scissors
- js excel导出功能
- Android异常与性能优化相关面试问题-OOM异常面试问题详解
- java线程基础巩固---Thread中断Interrupt方法学习&;采用优雅的方式结束线程生命周期
- [易学易懂系列|rustlang语言|零基础|快速入门|(22)|宏Macro]
- 第七章 路由 76 路由传参-使用params方式传递路由参数
- nginx之";/";结尾
- Qt实现多国语言(即界面翻译)可实时进行切换
- 炫酷CSS3垂直时间轴特效
- windows查看服务的状态