您好,登錄后才能下訂單哦!
這篇“java中的CompletableFuture怎么用”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“java中的CompletableFuture怎么用”文章吧。
說明
1、JDK 8中引入了 CompletableFuture 類,實現(xiàn)了Future和CompletionStage接口.
為異步編程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。
2、功能是可以讓兩個或者多個進(jìn)行運算來產(chǎn)生結(jié)果。
實例
/** * @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(); // 異步執(zhí)行版本 testCompletableFuture(); stopWatch.stop(); System.out.println(stopWatch); } private static void testCompletableFuture() throws InterruptedException, ExecutionException { // 先執(zhí)行 doOneThing 任務(wù),后執(zhí)行 doOtherThing 任務(wù) CompletableFuture<String> resultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing); // 獲取任務(wù)結(jié)果 String doOneThingResult = resultFuture.get(); // 獲取執(zhí)行結(jié)果 System.out.println("DoOneThing and DoOtherThing execute finished. result = " + doOneThingResult); } }
以上就是關(guān)于“java中的CompletableFuture怎么用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。