Java CompletableFuture的使用詳解
它代表某個(gè)同步或異步計(jì)算的一個(gè)階段。你可以把它理解為是一個(gè)為了產(chǎn)生有價(jià)值最終結(jié)果的計(jì)算的流水線上的一個(gè)單元。這意味著多個(gè)指令可以鏈接起來從而一個(gè)階段的完成可以觸發(fā)下一個(gè)階段的執(zhí)行。
任務(wù)開啟supplyAsync 開啟一個(gè)子線程去執(zhí)行有返回結(jié)果
開啟一個(gè)子線程用來執(zhí)行執(zhí)行事務(wù),可以通過返回值的join來得到返回值.
例如:
print('去煮飯了');CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { print('煮飯中....'); sleep(); sleep(); sleep(); print('煮飯完成'); return '盛米飯';});sleep();print('炒完菜了');sleep();print(completableFuture.join()+'!開吃');
返回結(jié)果:
runAsync 開啟一個(gè)子線程去執(zhí)行無結(jié)果
任務(wù)結(jié)束getjoin 獲得返回值
join 隱性拋出異常、get顯性拋出異常
Stopwatch stopwatch = Stopwatch.createStarted();CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 16 / 2);CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 27 / 3);try { Assertions.assertEquals(future1.get(),8);} catch (InterruptedException e) { e.printStackTrace();} catch (ExecutionException e) { e.printStackTrace();}Assertions.assertEquals(future2.join(),9);串行任務(wù)thenApplythenApplyAsync 串行將異步結(jié)果進(jìn)行同步異步的處理
在當(dāng)前階段正常執(zhí)行完成后(正常執(zhí)行是指沒有拋出異常)對前者的結(jié)果進(jìn)行的操作。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 16 / 2).thenApply(t1 -> t1*2);Assertions.assertEquals(future.join(),16);handlehandleAsync 允許有異常的情況下任然進(jìn)行異步任務(wù)執(zhí)行
handle方法和 thenApply方法處理方式基本一樣。不同的是 handle是在任務(wù)完成后再執(zhí)行,還可以處理異常的任務(wù)。thenApply只可以執(zhí)行正常的任務(wù),任務(wù)出現(xiàn)異常則不執(zhí)行 thenApply方法。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 16 / 0).handle((t1, e) -> { System.out.println('handle=' + e.getMessage()); return Integer.MAX_VALUE;});Assertions.assertEquals(future.join(),Integer.MAX_VALUE);thenAcceptthenAcceptAsync 同步異步穿行消費(fèi)前任務(wù)無返回結(jié)果
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> getRemoteUser(familyName)).thenAccept(list -> list.forEach(System.out::println));System.out.println(String.format('總執(zhí)行耗時(shí)[%d]毫秒', stopwatch.elapsed(TimeUnit.MILLISECONDS)));future.join();thenRunthenRunAsync 不關(guān)注前任務(wù)的執(zhí)行結(jié)果
不關(guān)心任務(wù)的處理結(jié)果。只要上面的任務(wù)正確的執(zhí)行完成,就開始執(zhí)行。同樣其也無返回值
CompletableFuture future = CompletableFuture.supplyAsync(() -> 12 / 1).thenRun(() -> System.out.println('無返回值的執(zhí)行')); System.out.println(future.join());thenComposethenComposeAsync 允許多個(gè)任務(wù)Future流水線執(zhí)行
允許你對兩個(gè)任務(wù)進(jìn)行流水線操作,第一個(gè)操作完成時(shí),將其結(jié)果作為參數(shù)傳遞給第二個(gè)操作。你可以將多個(gè)任務(wù)嵌套的進(jìn)行見例2
例1:
print('去煮飯了');CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { print('煮飯中....'); sleep(); sleep(); print('煮飯完成'); return '米飯';}).thenCompose(rice -> CompletableFuture.supplyAsync(() ->{ print('洗碗'); sleep(); print('洗碗洗完了'); return rice+'盛好了';}));sleep();print('炒完菜了');print(completableFuture.join()+'!開吃');
返回結(jié)果:
例2:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 16 / 2) .thenComposeAsync(t1 -> CompletableFuture.supplyAsync(() -> t1 / 2) .thenComposeAsync(t2 -> CompletableFuture.supplyAsync(() -> t2 / 2)));Assertions.assertEquals(future.join(),2);
結(jié)論:可以看出supplyAsync執(zhí)行了異步方法,thenCompose將上一個(gè)異步的結(jié)果(文中的rice)拿到以后通過一個(gè)線程去執(zhí)行了當(dāng)前異步任務(wù),并將結(jié)果在future.join()中輸出了。
whenCompletewhenCompleteAsync 串行將異步結(jié)果進(jìn)行同步異步的處理 與thenAccept很像,區(qū)別在于whenComplete的執(zhí)行會(huì)將前任務(wù)的返回結(jié)果給返回而thenAccept無返回結(jié)果。
//whenCompleteCompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 16 / 2);CompletableFuture<Integer> future = future1.whenComplete((t1, e) -> { Assertions.assertEquals(Thread.currentThread().getName(),'main'); Assertions.assertEquals(t1, 8); Assertions.assertNull(e); t1 = 10;});Assertions.assertEquals(future.join(), 8);//thenAcceptCompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 16 / 2);CompletableFuture<Void> future3 = future2.thenAccept(t1 -> { Assertions.assertEquals(Thread.currentThread().getName(), 'main'); Assertions.assertEquals(t1, 8);});Assertions.assertNull(future3.join());//thenApplyCompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> 16 / 2);CompletableFuture<Integer> future5 = future4.thenApply(t1 -> { Assertions.assertEquals(Thread.currentThread().getName(), 'main'); Assertions.assertEquals(t1, 8); return t1*2;});Assertions.assertEquals(future5.join(),16);System.out.println('------OK-------');并行任務(wù)thenCombine 并列多任務(wù)執(zhí)行并結(jié)果匯總
同時(shí)執(zhí)行兩個(gè)異步任務(wù),并且在最后通過BiFunction將兩個(gè)結(jié)果綜合起來進(jìn)行結(jié)果輸出.
例如:
print('去煮飯了');CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { print('煮飯中....'); sleep(); sleep(); print('煮飯完成'); return '米飯';}).thenCombine(CompletableFuture.supplyAsync(() ->{ print('洗碗'); sleep(); print('洗碗洗完了'); return '碗好了';}),(rice,bowl) -> { print('盛個(gè)飯'); return '盛個(gè)飯';});sleep();print('炒完菜了');print(completableFuture.join()+'!開吃');
返回結(jié)果:
結(jié)論:可以看出supplyAsync執(zhí)行了異步方法,thenCombine又起了一個(gè)新的線程并把兩者的結(jié)果綜合到一起(rice/bowl),由BiFunction進(jìn)行計(jì)算,并將結(jié)果在future.join()中輸出了。
thenAcceptBoththenAcceptBothAsync 并列多任務(wù)執(zhí)行并消費(fèi)結(jié)果無返回值與thenCombine差不多,區(qū)別是thenAcceptBoth無返回值
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 16 / 2).thenApply(t1 -> t1/2);CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 27 / 3).thenApply(t1 -> t1/3);CompletableFuture<Void> completableFuture = future1.thenAcceptBoth(future2, (t1, t2) -> { Assertions.assertEquals(t1 + t2, 7);});completableFuture.join();applyToEitherapplyToEitherAsync 兩個(gè)任務(wù)并行進(jìn)行用快的那個(gè)的結(jié)果作為后續(xù)處理
兩個(gè)任務(wù),誰執(zhí)行返回的結(jié)果快,我就用那個(gè)任務(wù)的結(jié)果進(jìn)行下一步的操作。
Stopwatch stopwatch = Stopwatch.createStarted();CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { sleep(Integer.MAX_VALUE); return 16 / 2;});CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 27 / 3);CompletableFuture<Integer> future = future1.applyToEither(future2, t -> t);Assertions.assertEquals(future.join(),9);Assertions.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 1000);runAfterBoth/runAfterBothAsync 兩個(gè)任務(wù)都完成了不關(guān)注執(zhí)行結(jié)果的進(jìn)行下一步操作
Stopwatch stopwatch = Stopwatch.createStarted();CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { sleep(2000); return 16 / 2;});CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 27 / 3);CompletableFuture<Void> future = future1.runAfterBothAsync(future2,() -> System.out.println('1234'));future.join();Assertions.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) > 2000);
以上就是Java CompletableFuture的使用詳解的詳細(xì)內(nèi)容,更多關(guān)于Java CompletableFuture的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 如何在jsp界面中插入圖片2. ASP實(shí)現(xiàn)加法驗(yàn)證碼3. python selenium 獲取接口數(shù)據(jù)的實(shí)現(xiàn)4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. 詳解JSP 內(nèi)置對象request常見用法6. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算7. Python matplotlib 繪制雙Y軸曲線圖的示例代碼8. jsp EL表達(dá)式詳解9. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除10. springboot集成與使用Sentinel的方法
