糖仁:舌尖上的甜蜜秘语,心尖上的温暖回响

核心内容摘要

鲁鲁社安App:数字时代的智慧安全管家,下载安装,即享安心_2_2
5G浪潮下的“奭”与变:中国通信行业的变革之路

WwwWx:一场关于“解压”的奇幻漂流

CompletableFuture.allOf() 概述CompletableFuture.allOf()是一个静态方法用于等待多个异步任务全部完成。

它返回一个新的CompletableFuture当所有给定的CompletableFuture都完成时这个新的 Future 也会完成。

基本语法public static CompletableFutureVoid allOf(CompletableFuture?... cfs)核心特性等待所有任务完成只有所有传入的 Future 都完成时返回的 Future 才会完成不收集结果返回的是CompletableFutureVoid不包含各个任务的结果异常处理如果任何一个任务异常完成返回的 Future 也会异常完成完整示例代码在您的项目中创建测试类package com.example.demo.completablefuture; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class CompletableFutureAllOfDemo { public static void main(String[] args) { System.out.println( CompletableFuture.allOf() 演示 ); // 示例1基本用法 basicAllOfExample(); // 示例2结合 Stream API allOfWithStreamExample(); // 示例3异常处理 allOfWithExceptionHandling(); // 示例4实际应用场景 practicalUseCaseExample(); } /** * 示例1基本用法 */ private static void basicAllOfExample() { System.out.println(\n--- 示例1基本用法 ---); // 创建3个异步任务 CompletableFutureString task1 CompletableFuture.supplyAsync(() - { sleep(

; return 任务1完成; }); CompletableFutureString task2 CompletableFuture.supplyAsync(() - { sleep(

; return 任务2完成; }); CompletableFutureString task3 CompletableFuture.supplyAsync(() - { sleep(

; return 任务3完成; }); // 使用 allOf 等待所有任务完成 CompletableFutureVoid allTasks CompletableFuture.allOf(task1, task2, task

; try { // 阻塞等待所有任务完成 allTasks.get(); System.out.println(所有任务已完成); // 获取各个任务的结果 System.out.println(任务1结果: task

get()); System.out.println(任务2结果: task

get()); System.out.println(任务3结果: task

get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } /** * 示例2结合 Stream API推荐用法 */ private static void allOfWithStreamExample() { System.out.println(\n--- 示例2结合 Stream API ---); // 创建任务列表 ListCompletableFutureString futures Arrays.asList( createAsyncTask(A,

, createAsyncTask(B,

, createAsyncTask(C,

, createAsyncTask(D,

); // 使用 allOf 等待所有任务完成然后收集结果 CompletableFutureVoid allFutures CompletableFuture.allOf( futures.toArray(new CompletableFuture[0]) ); // 所有任务完成后收集结果 CompletableFutureListString allResults allFutures.thenApply(v - futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList()) ); try { ListString results allResults.get(); System.out.println(所有任务结果: results); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } /** * 示例3异常处理 */ private static void allOfWithExceptionHandling() { System.out.println(\n--- 示例3异常处理 ---); CompletableFutureString successTask CompletableFuture.supplyAsync(() - { sleep(

; return 成功任务; }); CompletableFutureString failingTask CompletableFuture.supplyAsync(() - { sleep(

; throw new RuntimeException(任务执行失败); }); CompletableFutureVoid allTasks CompletableFuture.allOf(successTask, failingTask); // 异常处理方式1使用 exceptionally CompletableFutureVoid handled allTasks.exceptionally(throwable - { System.out.println(捕获到异常: throwable.getMessage()); return null; }); try { handled.get(); System.out.println(异常已处理完成); } catch (Exception e) { System.out.println(最终异常: e.getCause().getMessage()); } // 异常处理方式2使用 handle allTasks.handle((result, throwable) - { if (throwable ! null) { System.out.println(处理异常: throwable.getMessage()); } else { System.out.println(所有任务成功完成); } return null; }); } /** * 示例4实际应用场景 - 并行处理数据 */ private static void practicalUseCaseExample() { System.out.println(\n--- 示例4实际应用场景 - 并行处理数据 ---); // 模拟从不同数据源获取数据 CompletableFutureListString userData CompletableFuture.supplyAsync(() - { sleep(

; return Arrays.asList(用户1, 用户2, 用户

; }); CompletableFutureListString productData CompletableFuture.supplyAsync(() - { sleep(

; return Arrays.asList(产品A, 产品B, 产品C); }); CompletableFutureListString orderData CompletableFuture.supplyAsync(() - { sleep(

; return Arrays.asList(订单001, 订单

; }); // 等待所有数据加载完成 CompletableFutureVoid allDataLoaded CompletableFuture.allOf( userData, productData, orderData ); // 所有数据加载完成后进行业务处理 CompletableFutureString businessProcess allDataLoaded.thenApply(v - { try { ListString users userData.get(); ListString products productData.get(); ListString orders orderData.get(); System.out.println(用户数据: users); System.out.println(产品数据: products); System.out.println(订单数据: orders); return 业务处理完成共处理: users.size() 用户, products.size() 产品, orders.size() 订单; } catch (Exception e) { throw new RuntimeException(业务处理失败, e); } }); try { String result businessProcess.get(); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } /** * 创建异步任务的辅助方法 */ private static CompletableFutureString createAsyncTask(String name, int seconds) { return CompletableFuture.supplyAsync(() - { System.out.println(任务 name 开始执行预计耗时: seconds 秒); sleep(seconds); return 任务 name 完成; }); } /** * 模拟耗时操作的辅助方法 */ private static void sleep(int seconds) { try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }关键要点说明

结果收集技巧// 正确方式先等待所有完成再分别获取结果 CompletableFutureVoid all CompletableFuture.allOf(future1, future2, future

; all.thenRun(() - { String result1 future

join(); // 此时所有任务已完成join()不会阻塞 String result2 future

join(); String result3 future

join(); });

与 anyOf() 的区别// allOf(): 所有任务都完成 CompletableFuture.allOf(task1, task2, task

; // 三个都完成才算完成 // anyOf(): 任意一个任务完成 CompletableFuture.anyOf(task1, task2, task

; // 任意一个完成就算完成

性能优化建议// 使用自定义线程池提高性能 ExecutorService executor Executors.newFixedThreadPool(

; CompletableFutureString task1 CompletableFuture.supplyAsync(() - { // 耗时操作 return 结果; }, executor); // 指定线程池 // 记得关闭线程池 executor.shutdown();

总结CompletableFuture.allOf()的

核心价值✅并行执行多个异步任务同时执行✅统一等待无需手动管理多个 Future 的完成状态✅结果聚合可以方便地收集所有任务的结果✅异常传播任何一个任务失败都会导致整体失败适用场景并行调用多个微服务同时从多个数据源加载数据批量处理任务需要等待所有完成分布式计算结果的聚合CompletableFuture 常用方法详解基于您的代码环境我来为您详细介绍CompletableFuture的常用方法。

核心方法分类

创建异步任务//

1 创建无返回值的异步任务 CompletableFutureVoid runAsyncTask CompletableFuture.runAsync(() - { System.out.println(异步执行任务); }); //

2 创建有返回值的异步任务 CompletableFutureString supplyAsyncTask CompletableFuture.supplyAsync(() - { return 异步任务结果; }); //

3 使用自定义线程池 ExecutorService executor Executors.newFixedThreadPool(

; CompletableFutureString taskWithExecutor CompletableFuture.supplyAsync(() - { return 使用自定义线程池; }, executor);

结果处理链式调用//

1 thenApply - 同步转换结果 CompletableFutureString future CompletableFuture.supplyAsync(() - Hello) .thenApply(result - result World) .thenApply(String::toUpperCase); //

2 thenApplyAsync - 异步转换结果 CompletableFutureString asyncFuture CompletableFuture.supplyAsync(() - Hello) .thenApplyAsync(result - result World); // 在新线程中执行 //

3 thenAccept - 消费结果无返回值 CompletableFuture.supplyAsync(() - Hello) .thenAccept(result - System.out.println(结果: result)); //

4 thenRun - 任务完成后执行不依赖结果 CompletableFuture.supplyAsync(() - Hello) .thenRun(() - System.out.println(任务完成));

组合多个 Future//

1 thenCompose - 链式依赖前一个结果作为下一个的输入 CompletableFutureString composed CompletableFuture.supplyAsync(() - 用户ID) .thenCompose(userId - getUserInfo(userId)); //

2 thenCombine - 合并两个独立任务的结果 CompletableFutureString future1 CompletableFuture.supplyAsync(() - Hello); CompletableFutureString future2 CompletableFuture.supplyAsync(() - World); CompletableFutureString combined future

thenCombine(future2, (r1, r

- r1 r

; //

3 allOf - 等待所有任务完成您代码中的用法 CompletableFutureVoid allTasks CompletableFuture.allOf(task1, task2, task

; //

4 anyOf - 任意一个任务完成 CompletableFutureObject anyTask CompletableFuture.anyOf(task1, task2, task

;

异常处理//

1 exceptionally - 异常时提供默认值 CompletableFutureString safeFuture CompletableFuture.supplyAsync(() - { if (Math.random()

0.

throw new RuntimeException(错误); return 成功; }).exceptionally(throwable - 默认值); //

2 handle - 同时处理成功和异常情况 CompletableFutureString handled CompletableFuture.supplyAsync(() - 任务) .handle((result, throwable) - { if (throwable ! null) { return 错误处理; } return result 处理完成; }); //

3 whenComplete - 无论成功失败都执行类似 finally CompletableFuture.supplyAsync(() - 任务) .whenComplete((result, throwable) - { if (throwable ! null) { System.out.println(任务失败: throwable.getMessage()); } else { System.out.println(任务成功: result); } });完整示例代码在您的项目中创建新的演示类package com.example.demo.completablefuture; import java.util.concurrent.*; import java.util.function.Function; public class CompletableFutureMethodsDemo { public static void main(String[] args) throws Exception { System.out.println( CompletableFuture 常用方法演示 \n); //

创建任务演示 createTasksDemo(); //

结果处理演示 resultProcessingDemo(); //

组合任务演示 combineTasksDemo(); //

异常处理演示 exceptionHandlingDemo(); //

实际应用场景 practicalScenarioDemo(); } /** *

创建任务演示 */ private static void createTasksDemo() throws Exception { System.out.println(---

创建任务演示 ---); // runAsync - 无返回值 CompletableFutureVoid runTask CompletableFuture.runAsync(() - { System.out.println(runAsync: 执行无返回值任务); }); runTask.get(); // supplyAsync - 有返回值 CompletableFutureString supplyTask CompletableFuture.supplyAsync(() - { System.out.println(supplyAsync: 执行有返回值任务); return 任务结果; }); System.out.println(supplyAsync 结果: supplyTask.get()); System.out.println(); } /** *

结果处理演示 */ private static void resultProcessingDemo() throws Exception { System.out.println(---

结果处理演示 ---); // thenApply 链式调用 CompletableFutureString chain CompletableFuture.supplyAsync(() - { System.out.println(第一步: 获取原始数据); return 原始数据; }) .thenApply(data - { System.out.println(第二步: 处理数据); return data - 处理后; }) .thenApply(data - { System.out.println(第三步: 格式化数据); return data.toUpperCase(); }); System.out.println(链式调用结果: chain.get()); // thenAccept 消费结果 CompletableFuture.supplyAsync(() - 消费数据) .thenAccept(result - System.out.println(thenAccept: result)) .get(); System.out.println(); } /** *

组合任务演示 */ private static void combineTasksDemo() throws Exception { System.out.println(---

组合任务演示 ---); // thenCompose - 链式依赖 CompletableFutureString userInfo CompletableFuture.supplyAsync(() - 用户

.thenCompose(userId - CompletableFuture.supplyAsync(() - 用户信息: userId)); System.out.println(thenCompose 结果: userInfo.get()); // thenCombine - 合并结果 CompletableFutureString hello CompletableFuture.supplyAsync(() - Hello); CompletableFutureString world CompletableFuture.supplyAsync(() - World); CompletableFutureString combined hello.thenCombine(world, (h, w) - h w !); System.out.println(thenCombine 结果: combined.get()); System.out.println(); } /** *

异常处理演示 */ private static void exceptionHandlingDemo() throws Exception { System.out.println(---

异常处理演示 ---); // exceptionally - 异常时提供默认值 CompletableFutureString withException CompletableFuture.supplyAsync(() - { throw new RuntimeException(模拟异常); }).exceptionally(throwable - 异常处理: throwable.getMessage()); System.out.println(exceptionally 结果: withException.get()); // handle - 统一处理成功和失败 CompletableFutureString handled CompletableFuture.supplyAsync(() - 成功数据) .handle((result, throwable) - { if (throwable ! null) { return 处理异常: throwable.getMessage(); } return 处理成功: result; }); System.out.println(handle 结果: handled.get()); System.out.println(); } /** *

实际应用场景 */ private static void practicalScenarioDemo() throws Exception { System.out.println(---

实际应用场景 ---); // 场景用户注册流程 CompletableFutureString registerProcess CompletableFuture.supplyAsync(() - { System.out.println(

验证用户信息); return 用户验证通过; }) .thenCompose(verifyResult - CompletableFuture.supplyAsync(() - { System.out.println(

创建用户账户); return 账户创建成功; })) .thenCompose(accountResult - CompletableFuture.supplyAsync(() - { System.out.println(

发送欢迎邮件); return 邮件发送成功; })) .handle((result, throwable) - { if (throwable ! null) { return 注册失败: throwable.getMessage(); } return 注册成功: result; }); System.out.println(注册流程结果: registerProcess.get()); } }方法对比

总结方法类别方法名作用返回值创建任务runAsync()异步执行无返回值任务CompletableFutureVoidsupplyAsync()异步执行有返回值任务CompletableFutureT结果处理thenApply()同步转换结果CompletableFutureUthenApplyAsync()异步转换结果CompletableFutureUthenAccept()消费结果CompletableFutureVoidthenRun()任务完成后执行CompletableFutureVoid组合任务thenCompose()链式依赖CompletableFutureUthenCombine()合并两个结果CompletableFutureVallOf()等待所有完成CompletableFutureVoidanyOf()等待任意完成CompletableFutureObject异常处理exceptionally()异常时提供默认值CompletableFutureThandle()统一处理成功失败CompletableFutureUwhenComplete()完成时回调CompletableFutureT最佳实践建议使用join()替代get()在确定不会抛出检查异常时使用合理使用自定义线程池避免使用默认的 ForkJoinPool 导致资源竞争异常处理要全面使用handle()或exceptionally()处理可能的异常避免阻塞操作在异步任务中不要执行阻塞操作合理使用链式调用保持代码的可读性和维护性CompletableFuture.join() 和 CompletableFuture.get() 的区别基于您的代码环境我来详细解释这两个方法的区别核心区别对比特性join()get()异常处理抛出非检查异常(CompletionException)抛出检查异常(InterruptedException,ExecutionException)方法签名public T join()public T get() throws InterruptedException, ExecutionException使用场景Lambda表达式、Stream操作中更简洁需要精确处理异常的场景代码简洁性✅ 更简洁无需try-catch❌ 需要处理检查异常代码示例演示在您的项目中创建测试类package com.example.demo.completablefuture; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class JoinVsGetDemo { public static void main(String[] args) { System.out.println( join() vs get() 区别演示 \n); //

正常情况下的使用 normalUsageDemo(); //

异常情况下的处理 exceptionHandlingDemo(); //

实际应用场景对比 practicalComparisonDemo(); } /** *

正常情况下的使用 */ private static void normalUsageDemo() { System.out.println(---

正常情况下的使用 ---); CompletableFutureString future CompletableFuture.supplyAsync(() - Hello World); // 使用 get() - 需要处理检查异常 try { String result1 future.get(); System.out.println(get() 结果: result

; } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } // 使用 join() - 更简洁 String result2 future.join(); System.out.println(join() 结果: result

; System.out.println(); } /** *

异常情况下的处理 */ private static void exceptionHandlingDemo() { System.out.println(---

异常情况下的处理 ---); CompletableFutureString failingFuture CompletableFuture.supplyAsync(() - { throw new RuntimeException(任务执行失败); }); // get() 的异常处理 try { String result failingFuture.get(); System.out.println(get() 成功: result); } catch (InterruptedException e) { System.out.println(get() - 线程中断: e.getMessage()); Thread.currentThread().interrupt(); // 恢复中断状态 } catch (ExecutionException e) { System.out.println(get() - 执行异常: e.getCause().getMessage()); } // join() 的异常处理 try { String result failingFuture.join(); System.out.println(join() 成功: result); } catch (Exception e) { System.out.println(join() - 异常类型: e.getClass().getSimpleName()); System.out.println(join() - 异常信息: e.getCause().getMessage()); } System.out.println(); } /** *

实际应用场景对比 */ private static void practicalComparisonDemo() { System.out.println(---

实际应用场景对比 ---); // 场景在 Stream 操作中使用 System.out.println(在 Stream 操作中的使用:); // 使用 join() - 更简洁 CompletableFutureString future1 CompletableFuture.supplyAsync(() - 结果

; CompletableFutureString future2 CompletableFuture.supplyAsync(() - 结果

; CompletableFutureString future3 CompletableFuture.supplyAsync(() - 结果

; // 使用 join() 在 Stream 中很自然 CompletableFutureVoid allFutures CompletableFuture.allOf(future1, future2, future

; allFutures.thenRun(() - { // 这里使用 join() 很合适因为所有任务已经完成 String combined future

join() , future

join() , future

join(); System.out.println(Stream 中使用 join(): combined); }).join(); // 这里也使用 join() System.out.println(); // 场景需要精确异常处理时使用 get() System.out.println(需要精确异常处理时:); CompletableFutureString criticalFuture CompletableFuture.supplyAsync(() - { // 模拟关键业务操作 if (Math.random()

0.

{ throw new RuntimeException(关键业务失败); } return 关键业务成功; }); try { String criticalResult criticalFuture.get(); // 使用 get() 进行精确异常处理 System.out.println(关键业务结果: criticalResult); // 可以根据不同的异常类型进行不同的处理 } catch (InterruptedException e) { // 线程中断 - 可能需要执行清理操作 System.out.println(业务被中断执行清理...); Thread.currentThread().interrupt(); } catch (ExecutionException e) { // 业务执行异常 - 记录日志并返回错误信息 System.out.println(业务执行失败: e.getCause().getMessage()); // 可以在这里进行重试或降级处理 } } /** *

性能考虑 */ private static void performanceConsideration() { System.out.println(---

性能考虑 ---); // join() 和 get() 在性能上没有显著差异 // 主要区别在于异常处理机制 long startTime System.currentTimeMillis(); CompletableFutureString future CompletableFuture.supplyAsync(() - { try { Thread.sleep(

; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return 性能测试; }); // 使用 join() String result1 future.join(); long joinTime System.currentTimeMillis() - startTime; // 重置 Future future CompletableFuture.completedFuture(性能测试); startTime System.currentTimeMillis(); try { String result2 future.get(); long getTime System.currentTimeMillis() - startTime; System.out.println(join() 耗时: joinTime ms); System.out.println(get() 耗时: getTime ms); System.out.println(性能差异可以忽略不计); } catch (Exception e) { e.printStackTrace(); } } }使用场景建议推荐使用join()的情况//

在 Lambda 表达式和 Stream 操作中 ListCompletableFutureString futures // ...; ListString results futures.stream() .map(CompletableFuture::join) // 简洁明了 .collect(Collectors.toList()); //

确定任务已经完成时 CompletableFutureVoid allDone CompletableFuture.allOf(future1, future

; allDone.join(); // 此时使用 join() 很安全 //

代码简洁性优先的场景 String result asyncTask().join();推荐使用get()的情况//

需要精确处理不同异常类型时 try { String result criticalFuture.get(); } catch (InterruptedException e) { // 线程中断 - 需要特殊处理 Thread.currentThread().interrupt(); // 执行清理操作 } catch (ExecutionException e) { // 业务异常 - 记录日志或重试 logger.error(任务执行失败, e); } //

需要超时控制的场景 try { String result future.get(5, TimeUnit.SECONDS); // join() 没有超时版本 } catch (TimeoutException e) { // 处理超时 }⚠️重要

注意事项join()的陷阱// 错误用法在未完成的 Future 上直接使用 join() 可能阻塞 CompletableFutureString longRunningTask CompletableFuture.supplyAsync(() - { try { Thread.sleep(

; } catch (InterruptedException e) { /* ... */ } return 结果; }); // 这会阻塞当前线程5秒 String result longRunningTask.join(); // 谨慎使用get()的优势// 超时控制 try { String result future.get(2, TimeUnit.SECONDS); } catch (TimeoutException e) { // 2秒超时可以执行降级策略 result 默认值; } // 精确的异常区分 try { future.get(); } catch (InterruptedException e) { // 明确知道是线程中断 // 可以执行特定的中断处理逻辑 } catch (ExecutionException e) { // 明确知道是业务执行异常 // 可以获取具体的业务异常信息 }

总结选择标准推荐方法理由代码简洁性join()无需处理检查异常代码更简洁Lambda/Streamjoin()与函数式编程风格更契合精确异常处理get()可以区分线程中断和业务异常超时控制get()join()没有超时版本关键业务get()更安全的异常处理机制建议在大多数日常开发场景中特别是在函数式编程和Stream操作中优先使用join()以获得更简洁的代码。

在需要精确异常处理或超时控制的场景下使用get()。

在您的缓存服务和算法测试项目中根据具体场景灵活选择即可

P站下载-P站下载应用

百度百家号客服电话人工服务

123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123