這篇文章主要講解了“java中的CompletableFuture方式是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“java中的CompletableFuture方式是什么”吧!
說明
1、JDK 8中引入了 CompletableFuture 類,實現了Future和CompletionStage接口,為異步編程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。
2、功能是可以讓兩個或者多個進行運算來產生結果。
實例
/** * @author mghio * @since 2021-08-01 */ public class CompletableFutureDemo { public static CompletableFuture<String> doOneThing() { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "doOneThing"; }); } public static CompletableFuture<String> doOtherThing(String parameter) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return parameter + " " + "doOtherThing"; }); } public static void main(String[] args) throws ExecutionException, InterruptedException { StopWatch stopWatch = new StopWatch("CompletableFutureDemo"); stopWatch.start(); // 異步執行版本 testCompletableFuture(); stopWatch.stop(); System.out.println(stopWatch); } private static void testCompletableFuture() throws InterruptedException, ExecutionException { // 先執行 doOneThing 任務,后執行 doOtherThing 任務 CompletableFuture<String> resultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing); // 獲取任務結果 String doOneThingResult = resultFuture.get(); // 獲取執行結果 System.out.println("DoOneThing and DoOtherThing execute finished. result = " + doOneThingResult); } }
感謝各位的閱讀,以上就是“java中的CompletableFuture方式是什么”的內容了,經過本文的學習后,相信大家對java中的CompletableFuture方式是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。