說明
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的方法與範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!