paulwong

          CompletableFuture

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

          由于創(chuàng)建和銷毀線程是非常耗資源,因此改成線程建好后不銷毀,可以重用,用戶只需提供run方法的具體實(shí)現(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í)行線程,實(shí)現(xiàn)起來就有點(diǎn)復(fù)雜,于是CompletableFuture橫空出世。一共有50各方法可供使用。
          CompletableFuture.supplyAsync(),相當(dāng)于創(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 閱讀(305) 評論(0)  編輯  收藏 所屬分類: J2SE多線程

          主站蜘蛛池模板: 涡阳县| 五寨县| 德阳市| 新宁县| 平顶山市| 茌平县| 甘泉县| 神农架林区| 通榆县| 泸定县| 安义县| 民和| 大埔区| 屯留县| 常熟市| 永州市| 闽侯县| 贵溪市| 敦化市| 濮阳县| 祁阳县| 辽中县| 长葛市| 珲春市| 女性| 丰城市| 高碑店市| 五家渠市| 丰宁| 漳浦县| 岳普湖县| 建阳市| 安西县| 常德市| 麻阳| 嘉鱼县| 岳普湖县| 杭锦后旗| 平武县| 陇川县| 平山县|