Sfoglia il codice sorgente

add Cf01 demo:创建异步任务(runAsync/supplyAsync/completedFuture)

yangyi 1 settimana fa
parent
commit
3a3f0cf300
1 ha cambiato i file con 36 aggiunte e 0 eliminazioni
  1. 36 0
      src/main/java/space/anyi/Cf01_CreateStage.java

+ 36 - 0
src/main/java/space/anyi/Cf01_CreateStage.java

@@ -0,0 +1,36 @@
+package space.anyi;
+
+import java.util.concurrent.CompletableFuture;
+
+public class Cf01_CreateStage {
+    public static void main(String[] args) throws Exception {
+        // runAsync:执行一个没有返回值的异步任务
+        CompletableFuture<Void> voidFuture = CompletableFuture.runAsync(() -> {
+            System.out.println("runAsync 正在执行: " + Thread.currentThread().getName());
+        });
+        voidFuture.join(); // 阻塞等待任务完成
+
+        // supplyAsync:执行一个有返回值的异步任务
+        CompletableFuture<String> stringFuture = CompletableFuture.supplyAsync(() -> {
+            System.out.println("supplyAsync 正在执行: " + Thread.currentThread().getName());
+            return "Hello CompletableFuture";
+        });
+        System.out.println("supplyAsync 拿到的结果: " + stringFuture.get());
+
+        // completedFuture:直接得到一个已经完成的任务,避免起线程
+        CompletableFuture<Integer> done = CompletableFuture.completedFuture(42);
+        System.out.println("completedFuture 的结果: " + done.getNow(-1));
+
+        // getNow:任务已完成就返回结果,未完成不阻塞,直接返回默认值
+        CompletableFuture<String> slowTask = CompletableFuture.supplyAsync(() -> {
+            try {
+                Thread.sleep(500);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            return "完成了";
+        });
+        System.out.println("任务还没完成 getNow 返回: " + slowTask.getNow("默认值"));
+        System.out.println("阻塞等待任务结束得到: " + slowTask.join());
+    }
+}