|
@@ -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();
|
|
|
|
|
+ }
|
|
|
|
|
+}
|