2.示例
Random random = new Random();CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(random.nextInt(5));} catch (InterruptedException e) {e.printStackTrace();}return "hello";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(random.nextInt(1));} catch (InterruptedException e) {e.printStackTrace();}return "world";});CompletableFuture<Object> result = CompletableFuture.anyOf(future1, future2);【6】allOf
1.说明
//allOf方法用来实现多 CompletableFuture 的同时返回 。public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)2.示例
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("future1完成!");return "future1完成!";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {System.out.println("future2完成!");return "future2完成!";});CompletableFuture<Void> combindFuture = CompletableFuture.allOf(future1, future2);try {combindFuture.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}【4】CompletableFuture常用方法总结:
文章插图
【Future详解】
推荐阅读
- Go的网络编程详解
- gorm中的关联操作详解
- Go中的闭包、递归
- liunx之expect操作详解
- 条件期望:Conditional Expectation 举例详解之入门之入门之草履虫都说听懂了
- 深入理解AQS--jdk层面管程实现【管程详解的补充】
- 从缓存入门到并发编程三要素详解 Java中 volatile 、final 等关键字解析案例
- 补充部分---ScheduledThreadPoolExecutor类分析 线程池底层原理详解与源码分析
- Redis高并发分布式锁详解
- 5种分布式ID生成方案 分布式ID详解