Java并發(fā)編程(九) CompletableFuture

下面我們來分析一下java并發(fā)編程里的一個工具類CompletableFuture。我們知道,F(xiàn)uture機(jī)制是java中的一種異步獲取返回結(jié)果的方式,在jdk1.8中,提供了CompletableFuture這個類,能夠更好的操作Future,和處理返回的結(jié)果。
我們來看一下幾個方法。先來看一下supplyAsync方法

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                   Executor executor) {
    return asyncSupplyStage(screenExecutor(executor), supplier);
}

到asyncSupplyStage方法

static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
                                                 Supplier<U> f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<U> d = new CompletableFuture<U>();
    e.execute(new AsyncSupply<U>(d, f));
    return d;
}

調(diào)用execute方法執(zhí)行任務(wù)
再來看一下runAsync方法

public static CompletableFuture<Void> runAsync(Runnable runnable,
                                               Executor executor) {
    return asyncRunStage(screenExecutor(executor), runnable);
}

到asyncRunStage方法

static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<Void> d = new CompletableFuture<Void>();
    e.execute(new AsyncRun(d, f));
    return d;
}

也是調(diào)用execute方法執(zhí)行
anyOf:判斷多個CompletableFuture的執(zhí)行結(jié)果,其中任意一個執(zhí)行完返回執(zhí)行結(jié)果
allOf:多個CompletableFuture都執(zhí)行完返回執(zhí)行結(jié)果
thenCompose:同時執(zhí)行2個異步操作,將第一個CompletableFuture的返回值傳遞給第二個作為參數(shù)
thenCombine:結(jié)合2個CompletableFuture的執(zhí)行結(jié)果,通過一個BiFunction將2個Completable的返回值結(jié)合
thenApply:對返回結(jié)果進(jìn)行處理
thenAccept:消費返回的結(jié)果,無返回值
completeExceptionally:異常發(fā)生時的處理
whenComplete:任務(wù)執(zhí)行完,對返回的結(jié)果進(jìn)行處理
CompletableFuture的方法很多,可以對多個異步任務(wù)的返回結(jié)果進(jìn)行組合,處理。
CompletableFuture的分析就到這里了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容