1、測試異步調用:
static void testCompletableFuture1() throws ExecutionException, InterruptedException {// 1、無返回值的異步任務。異步線程執行RunnableCompletableFuture.runAsync(() -> System.out.println("only you"));// 2、有返回值的異步任務。執行Supplier函數并返回結果CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "3個時辰內必須找人解毒,不過老夫也可以幫忙哦");System.out.println("supplyAsync, result: " + future.get()); // 阻塞獲取結果}
打印:
2、鏈式調用:
static void testCompletableFuture2() throws ExecutionException, InterruptedException {System.out.println("main thread, id: " + Thread.currentThread().getId());// 鏈式操作CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync thread: " + Thread.currentThread().getId());return "我行我素";});// 結果轉換future = future.thenApply(s -> {System.out.println("thenApply thread: " + Thread.currentThread().getId());return s + " !!!";});// 結果消費CompletableFuture<Void> future2 = future.thenAccept(s -> {System.out.println("thenAccept thread: " + Thread.currentThread().getId());System.out.println(s);// 輸出結果});}
打印:
3、依賴其他Future任務
// thenCompose()串聯多個異步任務,前一個任務結果為后一個任務的輸入static void testCompletableFuture3() throws ExecutionException, InterruptedException {CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "haiyangxuanfeng");future = future.thenCompose(s -> CompletableFuture.supplyAsync(s::toUpperCase));future.thenAccept(new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}}).get();}
打印: