說明
1、JDK 8中引入了 CompletableFuture 類,實(shí)現(xiàn)了Future和CompletionStage接口.
為異步編程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。
2、功能是可以讓兩個或者多個進(jìn)行運(yùn)算來產(chǎn)生結(jié)果。
實(shí)例
/**
* @author mghio
* @since 2021-08-01
*/
public class CompletableFutureDemo {
public static CompletableFuturedoOneThing() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "doOneThing";
});
}
public static CompletableFuturedoOtherThing(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ù)
CompletableFutureresultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing);
// 獲取任務(wù)結(jié)果
String doOneThingResult = resultFuture.get();
// 獲取執(zhí)行結(jié)果
System.out.println("DoOneThing and DoOtherThing execute finished. result = " + doOneThingResult);
}
}
以上就是java中CompletableFuture方式的介紹,希望對大家有所幫助。更多關(guān)于“Java培訓(xùn)”的問題,歡迎咨詢千鋒教育在線名師。千鋒已有十余年的培訓(xùn)經(jīng)驗(yàn),課程大綱更科學(xué)更專業(yè),有針對零基礎(chǔ)的就業(yè)班,有針對想提升技術(shù)的好程序員班,高品質(zhì)課程助力你實(shí)現(xiàn)java程序員夢想。