這幾天稍微花時(shí)間學(xué)習(xí)了一下 java 8 提供的處理異步調(diào)用的一個(gè) future 類(lèi) CompletableFuture
.
這是一個(gè)針對(duì)函數(shù)式的 future 對(duì)象.用來(lái)讓我們更加優(yōu)雅的使用異步調(diào)用.
簡(jiǎn)述
CompletableFuture
是Future
接口的實(shí)現(xiàn)類(lèi).內(nèi)部只有兩個(gè)屬性:result
和stack
兩個(gè)值,分別表示對(duì)象所存儲(chǔ)的內(nèi)容以及對(duì)象現(xiàn)在的完成狀況.
由于CompletableFuture
也是 future 對(duì)象的一部分,所以它也有 future 的相關(guān)特性.博主在這里認(rèn)為它最終要的內(nèi)容就是他的執(zhí)行時(shí)間,就是:
CompletableFuture 只在對(duì)象創(chuàng)建的時(shí)候才開(kāi)始嘗試執(zhí)行
創(chuàng)建對(duì)象
CompletableFuture
有兩類(lèi)最基本的創(chuàng)建對(duì)象的靜態(tài)方法:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);
public static CompletableFuture<Void> runAsync(Runnable runnable);
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);
- supplyAsync 表示需要傳入一個(gè)
Supplier
類(lèi)型的 lambda 表達(dá)式來(lái)創(chuàng)建一個(gè)新的對(duì)象- runAsync 方法表示需要傳入一個(gè)
Runnable
類(lèi)型的對(duì)象來(lái)創(chuàng)建一個(gè)新的對(duì)象- supplyAsync 返回的對(duì)象帶有生成值,而 runAsync 方法返回的對(duì)象只能用來(lái)確認(rèn)該操作是否已經(jīng)完成而不能獲取到內(nèi)容.在這一點(diǎn)上和
Runnable
的情況有些類(lèi)似- 兩個(gè)方法都有對(duì)應(yīng)的重寫(xiě)方法, 需要傳入線(xiàn)程池,如果不傳入線(xiàn)程池,則會(huì)默認(rèn)使用
ForkJoinPool
線(xiàn)程池
獲取對(duì)象內(nèi)容
CompletableFuture
有幾個(gè)相關(guān)方法,包括:
public T get() throws InterruptedException, ExecutionException;
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
public T join();
public T getNow(T valueIfAbsent);
- get 方法會(huì)使當(dāng)前線(xiàn)程阻塞,并且等待直到 future 完成,并且將返回 future 的值
- 帶參數(shù)的 get 方法需要傳入對(duì)應(yīng)的時(shí)間長(zhǎng)度,一旦超出這個(gè)時(shí)間,會(huì)拋出
TimeoutException
其中
TimeUnit
是一個(gè)表示時(shí)間類(lèi)型的枚舉,最小單位:納秒,最大單位:日
[NANOSECONDS(納秒), MICROSECONDS(微秒), MILLISECONDS(毫秒), SECONDS(秒), MINUTES(分), HOURS(時(shí)), DAYS(日)]
- join 方法與 get 并無(wú)太大差別,但 join 方法不能被打斷.(暫時(shí)沒(méi)搞清楚)
- getNow 方法不會(huì)阻塞線(xiàn)程,而是立即返回值,如果該 future 當(dāng)前沒(méi)有完成,則會(huì)立刻返回該方法的傳入?yún)?shù).
- get 和 join 方法會(huì)在正常的情況下返回值,在遇到異常的情況下將異常拋出
完成對(duì)象
CompletableFuture
有兩個(gè)完成方法:
public boolean complete(T value);
public boolean completeExceptionally(Throwable ex);
public boolean cancel(boolean mayInterruptIfRunning);
- complete 方法將future狀態(tài)置為已完成,并且將參數(shù)注入,但如果這個(gè)future已經(jīng)完成了,則不會(huì)產(chǎn)生任何變化
- completeExceptionally 方法將future狀態(tài)置為已完成,并且將異常參數(shù)注入,并且在get的時(shí)候回獲取這個(gè)異常,但如果這個(gè)future已經(jīng)完成了,則不會(huì)產(chǎn)生任何變化
- cancel 方法會(huì)取消 future 對(duì)象,并且置入一個(gè) CancellationException. 參數(shù)表示是否會(huì)打斷 future 的執(zhí)行(目前沒(méi)有測(cè)試過(guò))
檢驗(yàn)方法
public boolean isDone();
public boolean isCancelled();
public boolean isCompletedExceptionally();
- isDone 用來(lái)返回 future 對(duì)象是否已經(jīng)完成
- isCancelled 用來(lái)返回 future 對(duì)象是否已經(jīng)被取消
- isCompletedExceptionally 用來(lái)返回 future 是否出現(xiàn)了異常
then 方法
CompletableFuture
有一系列延續(xù)方法,大部分都以 then 開(kāi)頭.
- 都表示在 future 對(duì)象已完成之后進(jìn)行某種操作.
- 方法都會(huì)返回一個(gè)新的
CompletableFuture
對(duì)象 - 方法的
Executor
參數(shù)表示是否需要傳入一個(gè)線(xiàn)程池來(lái)開(kāi)啟新線(xiàn)程操作 -
CompletableFuture
對(duì)象可以嵌套 - lambda中可以?huà)伋?RuntimeException .不可以?huà)伋?Exception.
//該方法的傳入一個(gè) T -> U 的Function<T,U>, 并且返回 <U> 的CompletableFuture
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor);
//傳入一個(gè) Consumer 函數(shù)來(lái)完成. 返回值沒(méi)有內(nèi)容
public CompletableFuture<Void> thenAccept(Consumer<? super T> action);
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);
//與 thenAccept 方法相同,但是傳入?yún)?shù)為 Runnable
public CompletableFuture<Void> thenRun(Runnable action);
public CompletableFuture<Void> thenRunAsync(Runnable action);
public CompletableFuture<Void> thenRunAsync(Runnable action,Executor executor);
//thenCombine 針對(duì)兩個(gè) future 進(jìn)行操作.
//需要傳入另一個(gè) future 以及 一個(gè) BiFunction<T,U,V> ,返回一個(gè)新的 future.
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor);
//thenAcceptBoth 同時(shí)等待兩個(gè) future ,并且返回一個(gè)空的CompletableFuture,
//Bi lambda 的兩個(gè)參數(shù)分別接受的兩個(gè)參數(shù) 第一個(gè)接受 this , 第二個(gè)接受第一個(gè)參數(shù)返回
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);
//和thenAcceptBoth方法相同,但是傳入?yún)?shù)為 Runnable
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);
//同時(shí)等待兩個(gè) future 同時(shí)完成 ,并且對(duì)第二個(gè)返回的 future 進(jìn)行處理.
public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn);
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn);
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn,Executor executor);
//同時(shí)等待兩個(gè) future ,并且對(duì)第二個(gè) future 的返回值進(jìn)行消費(fèi).
public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action);
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action);
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor);
//和 acceptEitherAsync 相同,并且傳入 Runnable
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action);
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);
//thenCompose 接受一個(gè) Function 并且返回一個(gè)新的 CompletableFuture 對(duì)象.
//所收集到的對(duì)象是沒(méi)有嵌套的 CompletableFuture 對(duì)象. 類(lèi)似 flatMap 的效果
public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,Executor executor);
//whenComplete 接受 future 中拋出的異常和返回
//在返回或者異常之后對(duì)返回值進(jìn)行消費(fèi),或者返回正常結(jié)果
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action);
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor);
//handleAsync 接受一個(gè) function<返回值,異常,結(jié)果> 并在返回之后對(duì) future 的相應(yīng)進(jìn)行處理
public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor);
//exceptionally 會(huì)返回一個(gè)新的 CompletableFuture, 并且該方法會(huì)阻塞當(dāng)前線(xiàn)程
//當(dāng)原有方法發(fā)生了異常,exceptionally 的 function 會(huì)執(zhí)行.
//當(dāng)原有方法正常完成,則會(huì)返回一個(gè)相同的結(jié)果
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn);
處理多個(gè)CompletableFuture
對(duì)于多個(gè)相互獨(dú)立的CompletableFuture
,我們提供了兩個(gè)方法來(lái)處理它們
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs);
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs);
allOf方法
- CompletableFuture.allOf 靜態(tài)方法,傳入多個(gè)獨(dú)立的 future ,并且返回一個(gè)新的CompletableFuture.
- 當(dāng)所有的 future 完成時(shí),新的 future 同時(shí)完成
- 不能傳入空值
- 當(dāng)某個(gè)方法出現(xiàn)了異常時(shí),新 future 會(huì)在所有 future 完成的時(shí)候完成,并且包含一個(gè)異常.
anyOf方法
- CompletableFuture.anyOf 靜態(tài)方法,傳入多個(gè)獨(dú)立的 future ,并且返回一個(gè)新的CompletableFuture
- 當(dāng)任何一個(gè)方法完成時(shí),新的 future 完成,并且返回該值
- 不能傳入空值
- 當(dāng)某個(gè)方法出現(xiàn)了異常時(shí),新 future 會(huì)立刻完成,并且攜帶一個(gè)異常
completedFuture 方法
- completedFuture 方法是能夠直接將值放入 future 對(duì)象,常用于測(cè)試
- CompletableFuture可以嵌套
public static <U> CompletableFuture<U> completedFuture(U value);
栗子
創(chuàng)建對(duì)象
@Test
public void base01() throws ExecutionException, InterruptedException {
/**
* CompletableFuture的靜態(tài)方法supplyAsync(Supplier<U> supplier)返回一個(gè)帶有
* ForkJoinPool 線(xiàn)程池的 CompletableFuture 對(duì)象.
* CompletableFuture 對(duì)象可以調(diào)用get方法,這樣會(huì)使線(xiàn)程阻塞.
* Supplier<T> 接口是一個(gè) () -> T 的函數(shù)
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println(future.get());
}
@Test
public void base02() throws ExecutionException, InterruptedException {
/**
* CompletableFuture的靜態(tài)方法supplyAsync(Supplier<U> supplier, Executor executor)
* 返回一個(gè)帶有自定義的線(xiàn)程池的CompletableFuture對(duì)象.
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt(), Executors.newCachedThreadPool());
System.out.println(future.get());
}
@Test
public void base03() throws ExecutionException, InterruptedException {
/**
* CompletableFuture的靜態(tài)方法 runAsync(Runnable runnable)返回一個(gè)帶有
* ForkJoinPool線(xiàn)程池的CompletableFuture對(duì)象.但是這個(gè)對(duì)象沒(méi)有返回值
*/
CompletableFuture future = CompletableFuture.runAsync(getRandomIntRunnable());
Assert.assertEquals(null,future.get());
}
@Test
public void base04() throws ExecutionException, InterruptedException {
/**
* CompletableFuture的靜態(tài)方法 runAsync(Runnable runnable, Executor executor)
* 返回一個(gè)帶有自定義的線(xiàn)程池的CompletableFuture對(duì)象.但是這個(gè)對(duì)象沒(méi)有返回值
*/
CompletableFuture future = CompletableFuture.runAsync(getRandomIntRunnable(), Executors.newCachedThreadPool());
Assert.assertEquals(null,future.get());
}
獲取對(duì)象內(nèi)容
@Test
public void base06() throws ExecutionException, InterruptedException, TimeoutException {
/**
* get(long,TimeUnit) 方法阻塞并且等待返回結(jié)果,TimeUnit表示時(shí)間長(zhǎng)度單位,最小是納秒.
* 當(dāng)超時(shí)未返回信息的時(shí)候回拋出TimeoutException異常
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println(future.get(10, TimeUnit.MILLISECONDS));
}
@Test
public void base07() throws ExecutionException, InterruptedException {
/**
* join 方法與 get 方法無(wú)基本差別
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println(future.join());
}
@Test
public void base08() throws ExecutionException, InterruptedException {
/**
* getNow(obj) 方法立即返回結(jié)果,如果無(wú)結(jié)果就返回傳入?yún)?shù)
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println(future.getNow("1bca"));
System.out.println(future.get());
}
完成對(duì)象
@Test
public void base09() throws ExecutionException, InterruptedException {
/**
* complete 方法將future狀態(tài)置為已完成,并且將參數(shù)注入,但如果這個(gè)future已經(jīng)完成了,則
* 不會(huì)產(chǎn)生任何變化
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
future.complete("123");
System.out.println(future.get());
future.complete("345");
System.out.println(future.get());
}
@Test
public void base10() throws ExecutionException, InterruptedException {
/**
* completeExceptionally 方法將future狀態(tài)置為已完成,并且將異常參數(shù)注入,
* 并且在get的時(shí)候回獲取這個(gè)異常
* 但如果這個(gè)future已經(jīng)完成了,則不會(huì)產(chǎn)生任何變化
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
future.complete("123");
System.out.println(future.get());
future.complete("345");
System.out.println(future.get());
future.completeExceptionally(new Exception("abc"));
System.out.println(future.get());
future = CompletableFuture.supplyAsync(getRandomInt());
future.completeExceptionally(new Exception("abc"));
System.out.println(future.get());
}
檢驗(yàn)方法
@Test
public void base20() throws ExecutionException, InterruptedException {
/**
* cancel 方法會(huì)取消 future 對(duì)象,并且置入一個(gè) CancellationException
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
// future.get();
future.cancel(false);
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
future.get();
}
then 方法
@Test
public void base11() throws ExecutionException, InterruptedException {
/**
* thenApplyAsync 方法會(huì)在前一個(gè)future *已完成* 的情況下開(kāi)始執(zhí)行方法中的lambda函數(shù).
* 并且返回一個(gè)新的future對(duì)象.
* 該方法的傳入一個(gè) T -> U 的Function<T,U>, 并且返回 <U> 的CompletableFuture
* 方法的參數(shù)表示是否需要傳入一個(gè)線(xiàn)程池來(lái)開(kāi)啟新線(xiàn)程操作
*/
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(getRandomInt());
System.out.println(new Date().getTime());
CompletableFuture<Integer> newFuture = future.thenApplyAsync(x -> {
System.out.println(new Date().getTime());
return x * 100;
});
//獲取兩個(gè)future的結(jié)果
System.out.println(future.get());
System.out.println(newFuture.get());
}
@Test
public void base12() throws ExecutionException, InterruptedException {
/**
* thenAcceptAsync 傳入一個(gè) Consumer 函數(shù)來(lái)完成.
* 其它與 thenApplyAsync 相同
* thenRunAsync 方法與此方法相同,但是傳入是一個(gè) Runnable
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture future1 = future.thenAcceptAsync(num -> {
System.out.println(num);
});
future.get();
System.out.println(future1.get());
}
@Test
public void base13() throws ExecutionException, InterruptedException {
/**
* thenCombine 針對(duì)兩個(gè) future 進(jìn)行操作.
* 需要傳入另一個(gè) future 以及 一個(gè) BiFunction<T,U,V> ,返回一個(gè)新的 future.
*/
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(getRandomInt(3000l));
CompletableFuture c = a.thenCombine(b,(a1,b1) -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return a1+b1;
});
System.out.println("a:"+a.get());
System.out.println("b:"+b.get());
System.out.println("c:"+c.get());
}
@Test
public void base14() throws ExecutionException, InterruptedException {
/**
* thenAcceptBoth 同時(shí)等待兩個(gè) future ,并且返回一個(gè)空的CompletableFuture,
* Bi lambda 的兩個(gè)參數(shù)分別接受的兩個(gè)參數(shù) 第一個(gè)接受 this , 第二個(gè)接受第一個(gè)參數(shù)返回
* runAfterBothAsync 方法和此方法相同,但是傳入?yún)?shù)為 Runnable
*/
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(getRandomInt(3000l));
a.thenAcceptBoth(b,(a1,b1) -> {
System.out.println(a1);
System.out.println(b1);
});
a.get();
b.get();
}
@Test
public void base15() throws ExecutionException, InterruptedException {
/**
* applyToEitherAsync 同時(shí)等待兩個(gè) future 同時(shí)完成 ,并且對(duì)第二個(gè)返回的 future 進(jìn)行處理.
* acceptEitherAsync 同時(shí)等待兩個(gè) future ,并且對(duì)第二個(gè) future 的返回值進(jìn)行消費(fèi).
* runAfterEitherAsync 和 acceptEitherAsync 相同,并且傳入 Runnable
*/
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(getRandomInt(3000l));
CompletableFuture c = a.applyToEitherAsync(b,b1 -> {
return b1*100;
});
a.get();
b.get();
System.out.println(c.get());
}
@Test
public void base16() throws ExecutionException, InterruptedException {
/**
* whenComplete 接受 future 中拋出的異常和返回, 方法中可以?huà)伋?RuntimeException .不可以?huà)伋?Exception.
* 在返回或者異常之后對(duì)返回值進(jìn)行消費(fèi),或者返回正常結(jié)果
* handleAsync 接受一個(gè) function<返回值,異常,結(jié)果> 并在返回之后對(duì) future 的相應(yīng)進(jìn)行處理
*/
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
int a = new Random().nextInt(10);
if(a > 5){
throw new RuntimeException("too big");
}
return a;
});
future.whenComplete((res,ex) -> {
System.out.println("result:"+res+", ex:"+ex);
});
}
@Test
public void base17() throws ExecutionException, InterruptedException {
/**
* exceptionally 會(huì)返回一個(gè)新的 CompletableFuture , 該方法會(huì)阻塞,
* 當(dāng)原有方法發(fā)生了異常,exceptionally 的 function 會(huì)執(zhí)行.
* 當(dāng)原有方法正常完成,則會(huì)返回一個(gè)相同的結(jié)果
*/
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException("except");
});
CompletableFuture exfuture = future.exceptionally(ex -> {return new Exception(((RuntimeException) ex).getMessage());});
System.out.println(exfuture.get());
}
@Test
public void base21() throws ExecutionException, InterruptedException {
/**
* thenCompose 接受一個(gè) Function 并且返回一個(gè)新的 CompletableFuture 對(duì)象.
* 所收集到的對(duì)象是沒(méi)有嵌套的 CompletableFuture 對(duì)象. 類(lèi)似 flatMap 的效果
*/
CompletableFuture future = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture newFuture = future.thenCompose(num -> {
return CompletableFuture.completedFuture(num);
});
System.out.println(newFuture.get());
}
處理多個(gè)CompletableFuture
allOf方法
@Test
public void base18() throws ExecutionException, InterruptedException {
/**
* CompletableFuture.allOf 靜態(tài)方法,傳入多個(gè)獨(dú)立的 future ,并且返回一個(gè)新的CompletableFuture
* 當(dāng)所有的 future 完成時(shí),新的 future 同時(shí)完成,
* 不能傳入空值
* 當(dāng)某個(gè)方法出現(xiàn)了異常時(shí),新 future 會(huì)在所有 future 完成的時(shí)候完成,并且包含一個(gè)異常.
*/
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(getRandomInt(3000l));
CompletableFuture ex = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("runtime");
});
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
CompletableFuture future = CompletableFuture.allOf(a,b,ex);
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
CompletableFuture exFuture = future.exceptionally( exp -> {
return ((RuntimeException) exp).getMessage();
});
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
System.out.println(exFuture.get());
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
}
anyOf方法
@Test
public void base19() throws ExecutionException, InterruptedException {
/**
* CompletableFuture.anyOf 靜態(tài)方法,傳入多個(gè)獨(dú)立的 future ,并且返回一個(gè)新的CompletableFuture
* 當(dāng)任何一個(gè)方法完成時(shí),新的 future 完成,并且返回該值
* 不能傳入空值
* 當(dāng)某個(gè)方法出現(xiàn)了異常時(shí),新 future 會(huì)立刻完成,并且攜帶一個(gè)異常
*/
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(getRandomInt());
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(getRandomInt(3000l));
CompletableFuture ex = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("runtime");
});
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
CompletableFuture future = CompletableFuture.anyOf(a,b,ex);
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
CompletableFuture exFuture = future.exceptionally( exp -> {
return ((RuntimeException) exp).getMessage();
});
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
System.out.println("is a done?" +a.isDone()+". Is b done?"+b.isDone()+".");
System.out.println(exFuture.get());
System.out.println("done?"+future.isDone()+" cancel?"+future.isCancelled()+" exp?"+future.isCompletedExceptionally());
}
completedFuture 方法
@Test
public void base22() throws ExecutionException, InterruptedException {
/**
* completedFuture 方法是能夠直接將值放入 future 對(duì)象,常用于測(cè)試
* CompletableFuture可以嵌套
*/
CompletableFuture future = CompletableFuture.completedFuture(1);
CompletableFuture future1 = CompletableFuture.completedFuture(future);
CompletableFuture future2 = CompletableFuture.completedFuture(future1);
System.out.println(future2.get());
}
這篇解析寫(xiě)到這里,下一次我會(huì)簡(jiǎn)單說(shuō)明一下有關(guān) java 8 中的幾種 lambda
歡迎關(guān)注我的博客: 既然來(lái)了就坐坐吧
小站剛開(kāi)始起步,歡迎您的駕到.