溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java中CompletableFuture的使用方法是什么

發(fā)布時間:2021-12-27 16:04:32 來源:億速云 閱讀:193 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“java中CompletableFuture的使用方法是什么”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

  java中CompletableFuture的使用

  CompletableFuture首先是一個Future,它擁有Future所有的功能,包括獲取異步執(zhí)行結(jié)果,取消正在執(zhí)行的任務(wù)等。

  除此之外,CompletableFuture還是一個CompletionStage。

  我們看下CompletableFuture的定義:

  public class CompletableFuture implements Future, CompletionStage

  什么是CompletionStage呢?

  在異步程序中,如果將每次的異步執(zhí)行都看成是一個stage的話,我們通常很難控制異步程序的執(zhí)行順序,在javascript中,我們需要在回調(diào)中執(zhí)行回調(diào)。這就會形成傳說中的回調(diào)地獄。

  好在在ES6中引入了promise的概念,可以將回調(diào)中的回調(diào)轉(zhuǎn)寫為鏈?zhǔn)秸{(diào)用,從而大大的提升了程序的可讀性和可寫性。

  同樣的在java中,我們使用CompletionStage來實現(xiàn)異步調(diào)用的鏈?zhǔn)讲僮鳌?/p>

  CompletionStage定義了一系列的then*** 操作來實現(xiàn)這一功能。

  CompletableFuture作為Future使用

  調(diào)用CompletableFuture.complete方法可以立馬返回結(jié)果,我們看下怎么使用這個方法來構(gòu)建一個基本的Future:

  public Future calculateAsync() throws InterruptedException {CompletableFuture completableFuture= new CompletableFuture<>();Executors.newCachedThreadPool().submit(() -> {Thread.sleep(500);completableFuture.complete("Hello");return null;});return completableFuture;}

  上面我們通過調(diào)動ExecutorService來提交一個任務(wù)從而得到一個Future。如果你知道執(zhí)行的結(jié)果,那么可以使用CompletableFuture的completedFuture方法來直接返回一個Future。

  public Future useCompletableFuture(){Future completableFuture =CompletableFuture.completedFuture("Hello");return completableFuture;}

  CompletableFuture還提供了一個cancel方法來立馬取消任務(wù)的執(zhí)行:

  public Future calculateAsyncWithCancellation() throws InterruptedException {CompletableFuture completableFuture = new CompletableFuture<>();Executors.newCachedThreadPool().submit(() -> {Thread.sleep(500);completableFuture.cancel(false);return null;});return completableFuture;}

  如果這個時候調(diào)用Future的get方法,將會報CancellationException異常。

  Future future = calculateAsyncWithCancellation();future.get(); // CancellationException

  異步執(zhí)行code

  CompletableFuture提供了runAsync和supplyAsync的方法,可以以異步的方式執(zhí)行代碼。

  我們看一個runAsync的基本應(yīng)用,接收一個Runnable參數(shù):

  public void runAsync(){CompletableFuture runAsync= CompletableFuture.runAsync(()->{log.info("runAsync");});}

  而supplyAsync接受一個Supplier:

  public void supplyAsync(){CompletableFuture supplyAsync=CompletableFuture.supplyAsync(()->{return "supplyAsync";});}

  他們兩個的區(qū)別是一個沒有返回值,一個有返回值。

  組合Futures

  上面講到CompletableFuture的一個重大作用就是將回調(diào)改為鏈?zhǔn)秸{(diào)用,從而將Futures組合起來。

  而鏈?zhǔn)秸{(diào)用的返回值還是CompletableFuture,我們看一個thenCompose的例子:

  CompletableFuture completableFuture

  = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));

  thenCompose將前一個Future的返回結(jié)果作為后一個操作的輸入。

  如果我們想合并兩個CompletableFuture的結(jié)果,則可以使用thenCombine:

  public void thenCombine(){CompletableFuture completableFuture= CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2));}

  如果你不想返回結(jié)果,則可以使用thenAcceptBoth:

  public void thenAcceptBoth(){CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),(s1, s2) -> System.out.println(s1 + s2));}

  thenApply() 和 thenCompose()的區(qū)別

  thenApply()和thenCompose()兩個方法都可以將CompletableFuture連接起來,但是兩個有點不一樣。

  thenApply()接收的是前一個調(diào)用返回的結(jié)果,然后對該結(jié)果進行處理。

  thenCompose()接收的是前一個調(diào)用的stage,返回flat之后的的CompletableFuture。

  簡單點比較,兩者就像是map和flatMap的區(qū)別。

  并行執(zhí)行任務(wù)

  當(dāng)我們需要并行執(zhí)行任務(wù)時,通常我們需要等待所有的任務(wù)都執(zhí)行完畢再去處理其他的任務(wù),那么我們可以用到CompletableFuture.allOf方法:

  public void allOf(){CompletableFuture future1= CompletableFuture.supplyAsync(() -> "Hello");CompletableFuture future2= CompletableFuture.supplyAsync(() -> "Beautiful");CompletableFuture future3= CompletableFuture.supplyAsync(() -> "World");CompletableFuture combinedFuture= CompletableFuture.allOf(future1, future2, future3);}

  allOf只保證task全都執(zhí)行,而并沒有返回值,如果希望帶有返回值,我們可以使用join:

  public void join(){CompletableFuture future1= CompletableFuture.supplyAsync(() -> "Hello");CompletableFuture future2= CompletableFuture.supplyAsync(() -> "Beautiful");CompletableFuture future3= CompletableFuture.supplyAsync(() -> "World");String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" "));}

  上面的程序?qū)祷兀骸癏ello Beautiful World”。

  異常處理

  如果在鏈?zhǔn)秸{(diào)用的時候拋出異常,則可以在最后使用handle來接收:

  北海房價走勢 http://house.bh.goufang.com/lpfangjia/

  public void handleError(){String name = null;CompletableFuture completableFuture= CompletableFuture.supplyAsync(() -> {if (name == null) {throw new RuntimeException("Computation error!");}return "Hello, " + name;}).handle((s, t) -> s != null ? s : "Hello, Stranger!");}

  這和Promise中的catch方法使用類似。

“java中CompletableFuture的使用方法是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI