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

最新文章

  1. 如何将已部署在ASM的资源迁移到ARM中
  2. ORA-12537: TNS:connection closed
  3. 关于onethink的迁移站点产生数据库错误
  4. 密码学初级教程(六)数字签名 Digital Signature
  5. 新一代IDE Light Table开源:让编程工作更简单
  6. 【转载】Linux动态库搜索路径的技巧
  7. footable动态载入数据
  8. 框架学习笔记:Unity3D的MVC框架——StrangeIoC
  9. PCB布线的地线干扰与抑制方法
  10. ADS-B 雷达 显示终端5.8
  11. 浅谈Swift和OC的区别
  12. PE文件详解(五)
  13. botzone Tetris2
  14. ELK+filebeat、kafka、zookeeper搭建文档
  15. ajax处理跨域有几种方式
  16. 理解WebKit和Chromium: Chromium插件和扩展基础
  17. TrieTree
  18. vsftpd.configro
  19. nginx 禁止恶意域名解析
  20. C++学习基础十七-- 函数指针

热门文章

  1. [ZOJ 3610] Yet Another Story of Rock-paper-scissors
  2. js excel导出功能
  3. Android异常与性能优化相关面试问题-OOM异常面试问题详解
  4. java线程基础巩固---Thread中断Interrupt方法学习&amp;采用优雅的方式结束线程生命周期
  5. [易学易懂系列|rustlang语言|零基础|快速入门|(22)|宏Macro]
  6. 第七章 路由 76 路由传参-使用params方式传递路由参数
  7. nginx之&quot;/&quot;结尾
  8. Qt实现多国语言(即界面翻译)可实时进行切换
  9. 炫酷CSS3垂直时间轴特效
  10. windows查看服务的状态