java中CompletableFuture的使用方法是什么

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

10年積累的網(wǎng)站建設(shè)、成都網(wǎng)站制作經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站設(shè)計(jì)制作后付款的網(wǎng)站建設(shè)流程,更有龍沙免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

java中CompletableFuture的使用

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

除此之外,CompletableFuture還是一個(gè)CompletionStage。

我們看下CompletableFuture的定義:

public class CompletableFuture implements Future, CompletionStage

什么是CompletionStage呢?

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

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

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

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

CompletableFuture作為Future使用

調(diào)用CompletableFuture.complete方法可以立馬返回結(jié)果,我們看下怎么使用這個(gè)方法來構(gòu)建一個(gè)基本的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來提交一個(gè)任務(wù)從而得到一個(gè)Future。如果你知道執(zhí)行的結(jié)果,那么可以使用CompletableFuture的completedFuture方法來直接返回一個(gè)Future。

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

CompletableFuture還提供了一個(gè)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;}

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

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

異步執(zhí)行code

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

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

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

而supplyAsync接受一個(gè)Supplier:

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

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

組合Futures

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

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

CompletableFuture completableFuture

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

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

如果我們想合并兩個(gè)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()兩個(gè)方法都可以將CompletableFuture連接起來,但是兩個(gè)有點(diǎn)不一樣。

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

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

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

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

當(dāng)我們需要并行執(zhí)行任務(wù)時(shí),通常我們需要等待所有的任務(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)用的時(shí)候拋出異常,則可以在最后使用handle來接收:

北海房價(jià)走勢 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)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

分享名稱:java中CompletableFuture的使用方法是什么
網(wǎng)站網(wǎng)址:http://www.muchs.cn/article24/gjghce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、網(wǎng)站設(shè)計(jì)公司、App設(shè)計(jì)、自適應(yīng)網(wǎng)站做網(wǎng)站、網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司