下面我們來分析一下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的分析就到這里了。