Przeglądaj źródła

add Cf02 demo:串行处理(thenApply/thenAccept/thenRun)

yangyi 1 tydzień temu
rodzic
commit
b9d701ad5b
1 zmienionych plików z 25 dodań i 0 usunięć
  1. 25 0
      src/main/java/space/anyi/Cf02_ThenSeries.java

+ 25 - 0
src/main/java/space/anyi/Cf02_ThenSeries.java

@@ -0,0 +1,25 @@
+package space.anyi;
+
+import java.util.concurrent.CompletableFuture;
+
+public class Cf02_ThenSeries {
+    public static void main(String[] args) throws Exception {
+        // 经典场景:下单 -> 扣库存 -> 记日志 -> 发通知,
+        // 每一步都依赖上一步的结果,用 thenXxx 串起来即可
+        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
+            System.out.println("1. 创建订单");
+            return "订单号 2024001";
+        }).thenApply(orderId -> {
+            System.out.println("2. 扣减库存,关联订单: " + orderId);
+            return orderId + " 已扣库存";
+        }).thenApply(info -> {
+            System.out.println("3. 记录日志: " + info);
+            return info + " 日志已落库";
+        }).thenAccept(result -> {
+            System.out.println("4. 打印流程结果: " + result);   // 只消费结果,无返回值
+        }).thenRun(() -> {
+            System.out.println("5. 发送短信通知(不关心数据)");  // 连结果都不关心
+        });
+        future.join();
+    }
+}