JAVA多線程之-CompletableFuture

CompletableFuture

創(chuàng)建

  • runAsync

    • 使用 runAsync() 運(yùn)行異步計(jì)算 如果你想異步的運(yùn)行一個(gè)后臺(tái)任務(wù)并且不想改任務(wù)返回任務(wù)東西术唬,這時(shí)候可以使用 CompletableFuture.runAsync()方法设捐,它持有一個(gè)Runnable對(duì)象借浊,并返回 CompletableFuture

    • CompletableFuture<Void> runnable_task = CompletableFuture.runAsync(() -> System.out.println("Runnable task")).whenComplete((v, t) -> {
                  //當(dāng)拋出異常的時(shí)候
                  if (t != null) {
                      t.printStackTrace();
                  }
              });
      s
      
  • supplyAsync:

    • 使用 supplyAsync() 運(yùn)行一個(gè)異步任務(wù)并且返回結(jié)果 , 它持有supplier 并且返回CompletableFuture<T> 是通過(guò)調(diào)用 傳入的supplier取得的值的類型萝招。

    • CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> "HELLO").whenComplete((v, t) -> {
                  try {
                      TimeUnit.SECONDS.sleep(5);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("whenComplete" + v);
              });
              System.out.println(stringCompletableFuture.get());
      

轉(zhuǎn)換&&消費(fèi)

  • thenApply&thenAccept:

    • thenApply接受一個(gè)Function接口(接受R返回T)類型參數(shù)蚂斤,并且繼續(xù)返回CompletableFuture<T>,對(duì)調(diào)用者CompletableFuture<?>進(jìn)行了轉(zhuǎn)換槐沼,注意與thenCompose區(qū)分橡淆,

    • thenAccept接受一個(gè)Comsumer(接受T無(wú)返回值)類型參數(shù),并且返回CompletableFuture<void>,可繼續(xù)進(jìn)行鏈?zhǔn)讲僮鳎?strong>消費(fèi)。

    • thenRun接受一個(gè)Runnable,該方法不能不能接收來(lái)自前面的參數(shù),通常用與鏈?zhǔn)降慕Y(jié)尾

    • CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> "HELLO").whenComplete((v, t) -> {
                  try {
                      TimeUnit.SECONDS.sleep(5);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("whenComplete" + v);
              });
      //thenApply接受一個(gè)Function接口(接受R返回T)類型參數(shù)母赵,并且繼續(xù)返回CompletableFuture<T>
      //thenAccept接受一個(gè)Comsumer(接受T無(wú)返回值)類型參數(shù),并且返回CompletableFuture<void>,可繼續(xù)進(jìn)行鏈?zhǔn)讲僮?//thenAccept接受一個(gè)Runnable,該方法不能不能接收來(lái)自前面的參數(shù),通常用與鏈?zhǔn)降慕Y(jié)尾
      stringCompletableFuture.thenApply(str -> str + "World").thenAccept(System.out::println).thenRun(() -> System.out.println("Done"));
      

組合:

  • thenCompose

    • thenCompose()用來(lái)連接兩個(gè)CompletableFuture逸爵,是生成一個(gè)新的CompletableFuture,并且前一個(gè)Future.get()會(huì)成為thenCompose的參數(shù)/注意與thenApply的區(qū)分

    • private static void thenCompose() {
             CompletableFuture.supplyAsync(() -> {
                 System.out.println("Start thenCompose 1");
                 try {
                     TimeUnit.SECONDS.sleep(3);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("End thenCompose 1");
                 return "HELLO WORLD";
             }).thenCompose(i -> CompletableFuture.supplyAsync(() -> {
                 System.out.println("Start thenCompose 2");
                 try {
                     TimeUnit.SECONDS.sleep(3);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("Start thenCompose 2");
                 return i.length();
             })).whenComplete((i, t) -> System.out.println(i));
         }
      
  • thenCombine:

    • combine可以用以接受一個(gè)新的Completable和一個(gè)BiFunction,調(diào)用者和傳入的CompletableFuture作為BiFunction的參數(shù),再返回一個(gè)CompletableFuture<T>,可繼續(xù)操作。

    • private static void thenCombine() {
              CompletableFuture.supplyAsync(() -> {
                  System.out.println("start thenCombine 1");
                  try {
                      TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(6));
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("end thenCombine 1");
                  return "12345";
              }).thenCombine(CompletableFuture.supplyAsync(() -> {
                  System.out.println("start thenCombine 2");
                  try {
                      TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(6));
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("end thenCombine 2");
                  return "6789";
              }), (i, j) -> i.length() > j.length()).whenComplete((b, t) -> System.out.println(b));
          }
      

完成時(shí)處理:

  • whenComplete

    • 接受一個(gè)調(diào)用者的future.get()以及可能出現(xiàn)的Throwable作為參數(shù),對(duì)結(jié)果進(jìn)行消費(fèi)BiConsumer

    • CompletableFuture.supplyAsync(() -> {
                 System.out.println("Start work");
                 sleep(2);
                 System.out.println("End work");
                 return "res";
             }).whenComplete((r, t) -> System.out.println(r));
      
  • exceptionally

    • 倘若出現(xiàn)異常接受異常并進(jìn)行處理:

    • CompletableFuture.supplyAsync(() -> {
                System.out.println("Start work");
                //sleep(2);
                System.out.println("End work");
                return "res";
            }).whenComplete((r, t) -> {
                System.out.println(r);
                if (t == null) {
                    System.out.println("No err");
                }
            });
      

MORE API

  • thenAcceptBoth

    • 該函數(shù)接受前面的future.get()作為h參數(shù)傳入BiConsumer,并接受本參數(shù)callable的future.get()作為w參數(shù)傳入BiConsumer

    • private static void acceptBoth() {
              CompletableFuture.supplyAsync(() -> {
                  System.out.println("Start task1");
                  try {
                      TimeUnit.SECONDS.sleep(10);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  return "Hello";
              }).thenAcceptBoth( //該函數(shù)接受前面的future.get()作為h參數(shù)傳入BiConsumer,并接受本參數(shù)callable的future.get()作為w參數(shù)傳入BiConsumer
                      CompletableFuture.supplyAsync(() -> "World"),
                      (h, w) -> System.out.println(h + "-----" + w));
          }
      
  • acceptEither

    • 取先完成的結(jié)果.但是沒(méi)完成的任務(wù)也將繼續(xù)執(zhí)行

    • private static void acceptEither() {
             CompletableFuture.supplyAsync(() -> {
                 System.out.println("Start Either1");
                 try {
                     TimeUnit.SECONDS.sleep(10);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("End Either2");
                 return "Either1";
             }).acceptEither(CompletableFuture.supplyAsync(() -> {
                 System.out.println("Start Either2");
                 try {
                     TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("End Either2");
                 return "Either2";
             }), i -> System.out.println("Final result " + i));
         }
      
  • runAfterBoth

    • 執(zhí)行完畢后調(diào)用Runnable,不消費(fèi)

    • private static void runAfterBoth() {
             CompletableFuture.supplyAsync(() -> {
                 System.out.println("start RunAfterBoth 1");
                 try {
                     TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(6));
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("end RunAfterBoth 1");
                 return "Task 1 Result";
             }).runAfterBoth(CompletableFuture.supplyAsync(() -> {
                 System.out.println("start RunAfterBoth 2");
                 try {
                     TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println("end RunAfterBoth 2");
                 return "Task 2 Result";
             }), () -> System.out.println("Done"));
         }
      
  • getNow

    • 在調(diào)用該方法時(shí)凹嘲,如果已經(jīng)CompleFuture已經(jīng)計(jì)算完成师倔,則返回future.get()的內(nèi)容,否者直接返回該方法的參數(shù)值(缺省)周蹭。

    • private static void getNow() throws InterruptedException {
              CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
                  try {
                      TimeUnit.SECONDS.sleep(2);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  return "Hello";
              });
              String now = stringCompletableFuture.getNow("NOWWWWWWWWWWWWWWWWWWWWWWWw");
              System.out.println(now);
              //output NOWWWWWWWWWWWWWWWWWWWWWWWw
              TimeUnit.SECONDS.sleep(3);
              now = stringCompletableFuture.getNow("NOWWWWWWWWWWWWWWWWWWWWWWWw");
              System.out.println(now);
              //output Hello
          }
      
  • complete

    • 類似于getNow方法趋艘,返回true的時(shí)候說(shuō)明CompletableFuture以及執(zhí)行完畢,該方法無(wú)效凶朗,返回false的時(shí)候瓷胧,說(shuō)明該方法設(shè)值成功,CompletableFuture尚未執(zhí)行完畢棚愤,調(diào)用future.get()將返回complete的參數(shù)值:

    • private static void complete() throws InterruptedException, ExecutionException {
              CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
                  try {
                      TimeUnit.SECONDS.sleep(2);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  return "World";
              });
              //通過(guò)注釋該行來(lái)進(jìn)行兩種情況的測(cè)試
              TimeUnit.SECONDS.sleep(3);
              stringCompletableFuture.complete("HELLO");
              System.out.println(stringCompletableFuture.get());
          }
      
  • join

    • 用法跟get一樣阻塞調(diào)用但是join不會(huì)拋出異常
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末搓萧,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子宛畦,更是在濱河造成了極大的恐慌瘸洛,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,464評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件次和,死亡現(xiàn)場(chǎng)離奇詭異反肋,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)踏施,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,033評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門石蔗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)罕邀,“玉大人,你說(shuō)我怎么就攤上這事养距∪忌伲” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,078評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵铃在,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我碍遍,道長(zhǎng)定铜,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,979評(píng)論 1 299
  • 正文 為了忘掉前任怕敬,我火速辦了婚禮揣炕,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘东跪。我一直安慰自己畸陡,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,001評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布虽填。 她就那樣靜靜地躺著丁恭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪斋日。 梳的紋絲不亂的頭發(fā)上牲览,一...
    開(kāi)封第一講書(shū)人閱讀 52,584評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音恶守,去河邊找鬼第献。 笑死,一個(gè)胖子當(dāng)著我的面吹牛兔港,可吹牛的內(nèi)容都是我干的庸毫。 我是一名探鬼主播,決...
    沈念sama閱讀 41,085評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼衫樊,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼飒赃!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起科侈,我...
    開(kāi)封第一講書(shū)人閱讀 40,023評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤盒揉,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后兑徘,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體刚盈,經(jīng)...
    沈念sama閱讀 46,555評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,626評(píng)論 3 342
  • 正文 我和宋清朗相戀三年挂脑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了藕漱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片欲侮。...
    茶點(diǎn)故事閱讀 40,769評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖肋联,靈堂內(nèi)的尸體忽然破棺而出威蕉,到底是詐尸還是另有隱情,我是刑警寧澤橄仍,帶...
    沈念sama閱讀 36,439評(píng)論 5 351
  • 正文 年R本政府宣布韧涨,位于F島的核電站,受9級(jí)特大地震影響侮繁,放射性物質(zhì)發(fā)生泄漏虑粥。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,115評(píng)論 3 335
  • 文/蒙蒙 一宪哩、第九天 我趴在偏房一處隱蔽的房頂上張望娩贷。 院中可真熱鬧,春花似錦锁孟、人聲如沸彬祖。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,601評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)储笑。三九已至,卻和暖如春圆恤,著一層夾襖步出監(jiān)牢的瞬間南蓬,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,702評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工哑了, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留赘方,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,191評(píng)論 3 378
  • 正文 我出身青樓弱左,卻偏偏與公主長(zhǎng)得像窄陡,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子拆火,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,781評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容