|
@@ -0,0 +1,45 @@
|
|
|
|
|
+package space.anyi;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.Arrays;
|
|
|
|
|
+import java.util.List;
|
|
|
|
|
+import java.util.concurrent.CompletableFuture;
|
|
|
|
|
+import java.util.stream.Collectors;
|
|
|
|
|
+
|
|
|
|
|
+public class Cf06_AllOfAnyOf {
|
|
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
|
|
+ // 场景: 一个页面需要同时调基础信息、库存、优惠三个接口,全部返回后才渲染
|
|
|
|
|
+ CompletableFuture<String> baseInfo = CompletableFuture.supplyAsync(() -> {
|
|
|
|
|
+ sleep(100);
|
|
|
|
|
+ return "基础信息";
|
|
|
|
|
+ });
|
|
|
|
|
+ CompletableFuture<String> stock = CompletableFuture.supplyAsync(() -> {
|
|
|
|
|
+ sleep(200);
|
|
|
|
|
+ return "库存信息";
|
|
|
|
|
+ });
|
|
|
|
|
+ CompletableFuture<String> coupon = CompletableFuture.supplyAsync(() -> {
|
|
|
|
|
+ sleep(300);
|
|
|
|
|
+ return "优惠信息";
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ // allOf: 等全部完成(返回 Void),再各自 join 汇总,让三路请求真正并行
|
|
|
|
|
+ CompletableFuture<Void> all = CompletableFuture.allOf(baseInfo, stock, coupon);
|
|
|
|
|
+ all.join();
|
|
|
|
|
+ List<String> data = Arrays.stream(new CompletableFuture[]{baseInfo, stock, coupon})
|
|
|
|
|
+ .map(CompletableFuture::join)
|
|
|
|
|
+ .map(Object::toString)
|
|
|
|
|
+ .collect(Collectors.toList());
|
|
|
|
|
+ System.out.println("allOf 全部就绪,汇总结果: " + String.join(" | ", data));
|
|
|
|
|
+
|
|
|
|
|
+ // anyOf: 任一路先完成即返回(结果是 Object),用于"谁先回来先给谁出结果"
|
|
|
|
|
+ CompletableFuture<Object> any = CompletableFuture.anyOf(baseInfo, stock, coupon);
|
|
|
|
|
+ System.out.println("anyOf 最先返回的一路: " + any.join());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static void sleep(long ms) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ Thread.sleep(ms);
|
|
|
|
|
+ } catch (InterruptedException e) {
|
|
|
|
|
+ e.printStackTrace();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|