paulwong

          My Links

          Blog Stats

          常用鏈接

          留言簿(67)

          隨筆分類(1392)

          隨筆檔案(1150)

          文章分類(7)

          文章檔案(10)

          相冊

          收藏夾(2)

          AI

          Develop

          E-BOOK

          Other

          養(yǎng)生

          微服務(wù)

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          60天內(nèi)閱讀排行

          CompletableFuture

          很久以前多線程是這樣創(chuàng)建:
          Thread t1 = new Thread();
          Thread t2 = new Thread();
          t1.start(); // 啟動新線程
          t2.start(); // 啟動新線程

          由于創(chuàng)建和銷毀線程是非常耗資源,因此改成線程建好后不銷毀,可以重用,用戶只需提供run方法的具體實現(xiàn):
          public static void main(String[] args) throws Exception {
                  ExecutorService executor = Executors.newSingleThreadExecutor();
                  Future<String> stringFuture = executor.submit(new Callable<String>() {
                      @Override
                      public String call() throws Exception {
                          Thread.sleep(2000);
                          return "async thread";
                      }
                  });
                  Thread.sleep(1000);
                  System.out.println("main thread");
                  System.out.println(stringFuture.get());

              }

          但如果很多線程被創(chuàng)建,并且線程間有依賴,即按流程和條件執(zhí)行線程,實現(xiàn)起來就有點復(fù)雜,于是CompletableFuture橫空出世。一共有50各方法可供使用。
          CompletableFuture.supplyAsync(),相當于創(chuàng)建了ExecutorService,同時也創(chuàng)建了Callable,然后提交到線程池中執(zhí)行。
          CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "任務(wù)A");
          CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> "任務(wù)B");
          CompletableFuture<String> futureC = futureB.thenApply(b -> {
                System.out.println("執(zhí)行任務(wù)C.");
                System.out.println("參數(shù):" + b);//參數(shù):任務(wù)B
                return "a";
          });


          !!How to use CompletableFuture and Callable in Java
          https://ducmanhphan.github.io/2020-02-10-How-to-use-CompletableFuture-Callable-in-Java/

          使用CompletableFuture優(yōu)化你的代碼執(zhí)行效率
          https://www.cnblogs.com/fingerboy/p/9948736.html

          CompletableFuture 使用詳解
          https://www.jianshu.com/p/6bac52527ca4

          使用CompletableFuture
          https://www.liaoxuefeng.com/wiki/1252599548343744/1306581182447650


          https://github.com/eugenp/tutorials/blob/master/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java

          posted on 2020-08-14 11:46 paulwong 閱讀(306) 評論(0)  編輯  收藏 所屬分類: J2SE多線程

          主站蜘蛛池模板: 隆化县| 新源县| 瑞安市| 花莲县| 滦南县| 合江县| 中西区| 沈丘县| 冕宁县| 成安县| 监利县| 阆中市| 安顺市| 三原县| 西和县| 习水县| 兴文县| 望谟县| 平顶山市| 永安市| 海原县| 江西省| 太仓市| 麟游县| 公主岭市| 新源县| 东至县| 皮山县| 额济纳旗| 内江市| 娱乐| 武强县| 长沙市| 昌宁县| 彝良县| 葵青区| 措勤县| 定西市| 犍为县| 梧州市| 茶陵县|