public class CompletableFutureTest { public static void main (String [] args) throws Exception { Test5 (); } / * * * whenCompleteAsync means are asynchronous incoming BiConsumer * whenComplete means is synchronous incoming BiConsumer * / public static void test1 () throws ExecutionException, InterruptedException { CompletableFuture <String> Future CompletableFuture.supplyAsync = (() -> " Hello " ); // future.whenCompleteAsync ((V, R & lt) -> { future.whenComplete ((V, R & lt) -> { the System.out.println("========="); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("====over====="); }); System.out.println("^^^^^^^^^^"); System.out.println(future.get()); Thread.currentThread().join(); } / * * * Also has both asynchronous and synchronous methods, thenApply no exception handling * @throws ExecutionException * @throws InterruptedException * / public static void test2 () throws ExecutionException, InterruptedException { CompletableFuture <Integer> = CompletableFuture.supplyAsync Future (() -> " Hello " ) .thenApply ((S) -> { the try { the System. OUT .println ( " ========== " ); TimeUnit.SECONDS.sleep ( . 5 ); } the catch (InterruptedException e) { e.printStackTrace(); } System.out.println("====over====="); return s.length(); }); // .thenApplyAsync((s) -> { // try { // System.out.println("=========="); // TimeUnit.SECONDS.sleep(5); // } catch (InterruptedException e) { // e.printStackTrace(); // } // System.out.println("====over====="); // return s.length(); // }); System.out.println("^^^^^^^^^^"); System.out.println(future.get()); Thread.currentThread().join(); } /** * handleAsync 有异常处理 * @throws ExecutionException * @throws InterruptedException */ public static void test3() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "hello") .handleAsync((v, t) -> { return v.length(); }); System.out.println(future.get()); } /** * thenAcceptAsync 直接将上一个的结果进行消费 * @throws ExecutionException * @throws InterruptedException */ public static void test4() throws ExecutionException, InterruptedException { CompletableFuture.supplyAsync(() -> "hello") .thenAcceptAsync((x) -> { System.out.println(x); }); } /** *执行完上一个future后再执行一个runnable * @throws ExecutionException * @throws InterruptedException */ public static void test5() throws ExecutionException, InterruptedException { CompletableFuture.supplyAsync(() -> "hello") .thenRunAsync(() -> { System.out.println("====over==="); }); } }