之前須要異步執行一個任務時,通常是用Thread或者線程池Executor去建立。若是須要返回值,則是調用Executor.submit獲取Future。可是多個線程存在依賴組合,咱們又能怎麼辦?可以使用同步組件CountDownLatch、CyclicBarrier等;其實有簡單的方法,就是用CompletableFuturejavascript
//使用內置線程ForkJoinPool.commonPool(),根據supplier構建執行任務 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) //指定自定義線程,根據supplier構建執行任務 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
//使用內置線程ForkJoinPool.commonPool(),根據runnable構建執行任務 public static CompletableFuture<Void> runAsync(Runnable runnable) //指定自定義線程,根據runnable構建執行任務 public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> rFuture = CompletableFuture .runAsync(() -> System.out.println("hello siting"), executor); //supplyAsync的使用 CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> { System.out.print("hello "); return "siting"; }, executor); //阻塞等待,runAsync 的future 無返回值,輸出null System.out.println(rFuture.join()); //阻塞等待 String name = future.join(); System.out.println(name); executor.shutdown(); // 線程池須要關閉 --------輸出結果-------- hello siting null hello siting
//有時候是須要構建一個常量的CompletableFuture public static <U> CompletableFuture<U> completedFuture(U value)
任務完成則運行action,不關心上一個任務的結果,無返回值java
public CompletableFuture<Void> thenRun(Runnable action) public CompletableFuture<Void> thenRunAsync(Runnable action) public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
CompletableFuture<Void> future = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenRunAsync(() -> System.out.println("OK"), executor); executor.shutdown(); --------輸出結果-------- OK
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenAcceptAsync(System.out::println, executor); executor.shutdown(); --------輸出結果-------- hello siting
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> "hello world", executor) .thenApplyAsync(data -> { System.out.println(data); return "OK"; }, executor); System.out.println(future.join()); executor.shutdown(); --------輸出結果-------- hello world OK
public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor)
//第一個異步任務,常量任務 CompletableFuture<String> f = CompletableFuture.completedFuture("OK"); //第二個異步任務 ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> "hello world", executor) .thenComposeAsync(data -> { System.out.println(data); return f; //使用第一個任務做爲返回 }, executor); System.out.println(future.join()); executor.shutdown(); --------輸出結果-------- hello world OK
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action) public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action) public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
//第一個異步任務,常量任務 CompletableFuture<String> first = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture //第二個異步任務 .supplyAsync(() -> "hello siting", executor) // () -> System.out.println("OK") 是第三個任務 .runAfterBothAsync(first, () -> System.out.println("OK"), executor); executor.shutdown(); --------輸出結果-------- OK
//第一個任務完成再運行other,fn再依賴消費兩個任務的結果,無返回值 public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) //兩個任務異步完成,fn再依賴消費兩個任務的結果,無返回值 public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) //兩個任務異步完成(第二個任務用指定線程池執行),fn再依賴消費兩個任務的結果,無返回值 public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor)
//第一個異步任務,常量任務 CompletableFuture<String> first = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture //第二個異步任務 .supplyAsync(() -> "hello siting", executor) // (w, s) -> System.out.println(s) 是第三個任務 .thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor); executor.shutdown(); --------輸出結果-------- hello siting
//第一個任務完成再運行other,fn再依賴消費兩個任務的結果,有返回值 public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) //兩個任務異步完成,fn再依賴消費兩個任務的結果,有返回值 public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) //兩個任務異步完成(第二個任務用指定線程池執行),fn再依賴消費兩個任務的結果,有返回值 public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)
//第一個異步任務,常量任務 CompletableFuture<String> first = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = CompletableFuture //第二個異步任務 .supplyAsync(() -> "hello siting", executor) // (w, s) -> System.out.println(s) 是第三個任務 .thenCombineAsync(first, (s, w) -> { System.out.println(s); return "OK"; }, executor); System.out.println(future.join()); executor.shutdown(); --------輸出結果-------- hello siting OK
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action) public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action) public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action, Executor executor)
//第一個異步任務,休眠1秒,保證最晚執行晚 CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} System.out.println("hello world"); return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture //第二個異步任務 .supplyAsync(() ->{ System.out.println("hello siting"); return "hello siting"; } , executor) //() -> System.out.println("OK") 是第三個任務 .runAfterEitherAsync(first, () -> System.out.println("OK") , executor); executor.shutdown(); --------輸出結果-------- hello siting OK
public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)
//第一個異步任務,休眠1秒,保證最晚執行晚 CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture //第二個異步任務 .supplyAsync(() -> "hello siting", executor) // data -> System.out.println(data) 是第三個任務 .acceptEitherAsync(first, data -> System.out.println(data) , executor); executor.shutdown(); --------輸出結果-------- hello siting
public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn) public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn) public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor)
//第一個異步任務,休眠1秒,保證最晚執行晚 CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = CompletableFuture //第二個異步任務 .supplyAsync(() -> "hello siting", executor) // data -> System.out.println(data) 是第三個任務 .applyToEitherAsync(first, data -> { System.out.println(data); return "OK"; } , executor); System.out.println(future); executor.shutdown(); --------輸出結果-------- hello siting OK
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
CompletableFuture<Integer> first = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> 1) .exceptionally(e -> { e.printStackTrace(); // 異常捕捉處理,前面兩個處理環節的平常都能捕獲 return 0; });
public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor)
CompletableFuture<Integer> first = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> 1) .handleAsync((data,e) -> { e.printStackTrace(); // 異常捕捉處理 return data; }); System.out.println(first.join()); --------輸出結果-------- java.util.concurrent.CompletionException: java.lang.RuntimeException: main error! ... 5 more null
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor)
CompletableFuture<AtomicBoolean> first = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> new AtomicBoolean(false)) .whenCompleteAsync((data,e) -> { //異常捕捉處理, 可是異常仍是會在外層復現 System.out.println(e.getMessage()); }); first.join(); --------輸出結果-------- java.lang.RuntimeException: main error! Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error! ... 5 more
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
CompletableFuture<Void> future = CompletableFuture .allOf(CompletableFuture.completedFuture("A"), CompletableFuture.completedFuture("B")); //所有任務都須要執行完 future.join(); CompletableFuture<Object> future2 = CompletableFuture .anyOf(CompletableFuture.completedFuture("C"), CompletableFuture.completedFuture("D")); //其中一個任務行完便可 future2.join();
// mayInterruptIfRunning 無影響;若是任務未完成,則返回異常 public boolean cancel(boolean mayInterruptIfRunning) //任務是否取消 public boolean isCancelled()
CompletableFuture<Integer> future = CompletableFuture .supplyAsync(() -> { try { Thread.sleep(1000); } catch (Exception e) { } return "hello world"; }) .thenApply(data -> 1); System.out.println("任務取消前:" + future.isCancelled()); // 若是任務未完成,則返回異常,須要對使用exceptionally,handle 對結果處理 future.cancel(true); System.out.println("任務取消後:" + future.isCancelled()); future = future.exceptionally(e -> { e.printStackTrace(); return 0; }); System.out.println(future.join()); --------輸出結果-------- 任務取消前:false 任務取消後:true java.util.concurrent.CancellationException at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276) at Test.main(Test.java:25) 0
// 任務是否執行完成 public boolean isDone() //阻塞等待 獲取返回值 public T join() // 阻塞等待 獲取返回值,區別是get須要返回受檢異常 public T get() //等待阻塞一段時間,並獲取返回值 public T get(long timeout, TimeUnit unit) //未完成則返回指定value public T getNow(T valueIfAbsent) //未完成,使用value做爲任務執行的結果,任務結束。須要future.get獲取 public boolean complete(T value) //未完成,則是異常調用,返回異常結果,任務結束 public boolean completeExceptionally(Throwable ex) //判斷任務是否因發生異常結束的 public boolean isCompletedExceptionally() //強制地將返回值設置爲value,不管該以前任務是否完成;相似complete public void obtrudeValue(T value) //強制地讓異常拋出,異常返回,不管該以前任務是否完成;相似completeExceptionally public void obtrudeException(Throwable ex)
CompletableFuture<Integer> future = CompletableFuture .supplyAsync(() -> { try { Thread.sleep(1000); } catch (Exception e) { } return "hello world"; }) .thenApply(data -> 1); System.out.println("任務完成前:" + future.isDone()); future.complete(10); System.out.println("任務完成後:" + future.join()); --------輸出結果-------- 任務完成前:false 任務完成後:10
Java 多線程一直是面試時候的重點,也是能力提高的重要體現,如何作到波瀾不驚,從容面對,須要咱們對其中的內容融匯貫通,小編這裏也對應總結了一份多線程-併發編程的思惟導圖,須要的朋友能夠看看,關注公衆號:麒麟改bug,還能夠領取一份包含了Java基礎、Java集合容器、Java異常、併發編程、JVM、Spring、Spring MVC、Spring Boot、Spring Cloud、MyBatis、Redis、MySQL數據庫、消息中間件MQ與RabbitMQ、Dubbo、Linux、Tomcat、ZooKeeper、Netty、 架構設計&分佈式&數據結構與算法等等,都是互聯網大廠的面試真題,已經有粉絲靠這份PDF拿下衆多大廠的offer。面試