Java CompletableFuture的使用詳解
它代表某個同步或異步計算的一個階段。你可以把它理解為是一個為了產生有價值最終結果的計算的流水線上的一個單元。這意味著多個指令可以鏈接起來從而一個階段的完成可以觸發下一個階段的執行。
任務開啟supplyAsync 開啟一個子線程去執行有返回結果
開啟一個子線程用來執行執行事務,可以通過返回值的join來得到返回值.
例如:
print('去煮飯了');CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { print('煮飯中....'); sleep(); sleep(); sleep(); print('煮飯完成'); return '盛米飯';});sleep();print('炒完菜了');sleep();print(completableFuture.join()+'!開吃');
返回結果:
runAsync 開啟一個子線程去執行無結果
任務結束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);串行任務thenApplythenApplyAsync 串行將異步結果進行同步異步的處理
在當前階段正常執行完成后(正常執行是指沒有拋出異常)對前者的結果進行的操作。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 16 / 2).thenApply(t1 -> t1*2);Assertions.assertEquals(future.join(),16);handlehandleAsync 允許有異常的情況下任然進行異步任務執行
handle方法和 thenApply方法處理方式基本一樣。不同的是 handle是在任務完成后再執行,還可以處理異常的任務。thenApply只可以執行正常的任務,任務出現異常則不執行 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 同步異步穿行消費前任務無返回結果
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> getRemoteUser(familyName)).thenAccept(list -> list.forEach(System.out::println));System.out.println(String.format('總執行耗時[%d]毫秒', stopwatch.elapsed(TimeUnit.MILLISECONDS)));future.join();thenRunthenRunAsync 不關注前任務的執行結果
不關心任務的處理結果。只要上面的任務正確的執行完成,就開始執行。同樣其也無返回值
CompletableFuture future = CompletableFuture.supplyAsync(() -> 12 / 1).thenRun(() -> System.out.println('無返回值的執行')); System.out.println(future.join());thenComposethenComposeAsync 允許多個任務Future流水線執行
允許你對兩個任務進行流水線操作,第一個操作完成時,將其結果作為參數傳遞給第二個操作。你可以將多個任務嵌套的進行見例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()+'!開吃');
返回結果:
例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);
結論:可以看出supplyAsync執行了異步方法,thenCompose將上一個異步的結果(文中的rice)拿到以后通過一個線程去執行了當前異步任務,并將結果在future.join()中輸出了。
whenCompletewhenCompleteAsync 串行將異步結果進行同步異步的處理 與thenAccept很像,區別在于whenComplete的執行會將前任務的返回結果給返回而thenAccept無返回結果。
//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-------');并行任務thenCombine 并列多任務執行并結果匯總
同時執行兩個異步任務,并且在最后通過BiFunction將兩個結果綜合起來進行結果輸出.
例如:
print('去煮飯了');CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { print('煮飯中....'); sleep(); sleep(); print('煮飯完成'); return '米飯';}).thenCombine(CompletableFuture.supplyAsync(() ->{ print('洗碗'); sleep(); print('洗碗洗完了'); return '碗好了';}),(rice,bowl) -> { print('盛個飯'); return '盛個飯';});sleep();print('炒完菜了');print(completableFuture.join()+'!開吃');
返回結果:
結論:可以看出supplyAsync執行了異步方法,thenCombine又起了一個新的線程并把兩者的結果綜合到一起(rice/bowl),由BiFunction進行計算,并將結果在future.join()中輸出了。
thenAcceptBoththenAcceptBothAsync 并列多任務執行并消費結果無返回值與thenCombine差不多,區別是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 兩個任務并行進行用快的那個的結果作為后續處理
兩個任務,誰執行返回的結果快,我就用那個任務的結果進行下一步的操作。
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 兩個任務都完成了不關注執行結果的進行下一步操作
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的使用詳解的詳細內容,更多關于Java CompletableFuture的資料請關注好吧啦網其它相關文章!
相關文章:
1. Django中的AutoField字段使用2. Django ORM實現按天獲取數據去重求和例子3. 解決docker與vmware的沖突問題4. IntelliJ Idea 2020.1 正式發布,官方支持中文(必看)5. IntelliJ IDEA設置自動提示功能快捷鍵的方法6. asp.net core應用docke部署到centos7的全過程7. Java 3D的動畫展示(Part1-使用JMF)8. Python基于jieba, wordcloud庫生成中文詞云9. 如何在vue3.0+中使用tinymce及實現多圖上傳文件上傳公式編輯功能10. 刪除docker里建立容器的操作方法
