CompletableFuture线程串行化方法
生活随笔
收集整理的這篇文章主要介紹了
CompletableFuture线程串行化方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
thenApply 方法:當(dāng)一個(gè)線程依賴另一個(gè)線程時(shí),獲取上一個(gè)任務(wù)返回的結(jié)果,并返回當(dāng)前任務(wù)的返回值。
thenAccept方法:消費(fèi)處理結(jié)果。接收任務(wù)的處理結(jié)果,并消費(fèi)處理,無(wú)返回結(jié)果。
thenRun方法:只要上面的任務(wù)執(zhí)行完成,就開始執(zhí)行thenRun,只是處理完任務(wù)后,執(zhí)行 thenRun的后續(xù)操作
帶有Async默認(rèn)是異步執(zhí)行的。這里所謂的異步指的是不在當(dāng)前線程內(nèi)執(zhí)行。
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)public CompletionStage<Void> thenAccept(Consumer<? super T> action); public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action); public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);public CompletionStage<Void> thenRun(Runnable action); public CompletionStage<Void> thenRunAsync(Runnable action); public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);Function<? super T,? extends U> T:上一個(gè)任務(wù)返回結(jié)果的類型 U:當(dāng)前任務(wù)的返回值類型
代碼演示:
public static void main(String[] args) throws ExecutionException, InterruptedException {CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {System.out.println(Thread.currentThread().getName() + "\t completableFuture");//int i = 10 / 0;return 1024;}}).thenApply(new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer o) {System.out.println("thenApply方法,上次返回結(jié)果:" + o);return o * 2;}}).whenComplete(new BiConsumer<Integer, Throwable>() {@Overridepublic void accept(Integer o, Throwable throwable) {System.out.println("-------o=" + o);System.out.println("-------throwable=" + throwable);}}).exceptionally(new Function<Throwable, Integer>() {@Overridepublic Integer apply(Throwable throwable) {System.out.println("throwable=" + throwable);return 6666;}});System.out.println(future.get()); }總結(jié)
以上是生活随笔為你收集整理的CompletableFuture线程串行化方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CompletableFuture计算完
- 下一篇: CompletableFuture多任务