Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

前言

之前須要異步執行一個任務時,通常是用Thread或者線程池Executor去建立。若是須要返回值,則是調用Executor.submit獲取Future。可是多個線程存在依賴組合,咱們又能怎麼辦?可以使用同步組件CountDownLatch、CyclicBarrier等;其實有簡單的方法,就是用CompletableFuturejavascript

  • 線程任務的建立
  • 線程任務的串行執行
  • 線程任務的並行執行
  • 處理任務結果和異常
  • 多任務的簡單組合
  • 取消執行線程任務
  • 任務結果的獲取和完成與否判斷

一、建立異步線程任務

根據supplier建立CompletableFuture任務

//使用內置線程ForkJoinPool.commonPool(),根據supplier構建執行任務
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//指定自定義線程,根據supplier構建執行任務
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

根據runnable建立CompletableFuture任務

//使用內置線程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返回

//有時候是須要構建一個常量的CompletableFuture
public static <U> CompletableFuture<U> completedFuture(U value)

2 、線程串行執行

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

任務完成則運行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

任務完成則運行action,依賴上一個任務的結果,無返回值

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

任務完成則運行fn,依賴上一個任務的結果,有返回值

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

thenCompose - 任務完成則運行fn,依賴上一個任務的結果,有返回值

  • 相似thenApply(區別是thenCompose的返回值是CompletionStage,thenApply則是返回 U),提供該方法爲了和其餘CompletableFuture任務更好地配套組合使用
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

3 、線程並行執行

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

兩個CompletableFuture[並行]執行完,而後執行action,不依賴上兩個任務的結果,無返回值

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

兩個CompletableFuture[並行]執行完,而後執行action,依賴上兩個任務的結果,無返回值

//第一個任務完成再運行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

兩個CompletableFuture[並行]執行完,而後執行action,依賴上兩個任務的結果,有返回值

//第一個任務完成再運行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

4 、線程並行執行,誰先執行完則誰觸發下一任務(兩者選其最快)

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

上一個任務或者other任務完成, 運行action,不依賴前一任務的結果,無返回值

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

上一個任務或者other任務完成, 運行action,依賴最早完成任務的結果,無返回值

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

上一個任務或者other任務完成, 運行fn,依賴最早完成任務的結果,有返回值

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

5 、處理任務結果或者異常

exceptionally-處理異常

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
  • 若是以前的處理環節有異常問題,則會觸發exceptionally的調用至關於 try...catch
  • 使用示例
CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("main error!");
            }
            return "hello world";
        })
        .thenApply(data -> 1)
        .exceptionally(e -> {
            e.printStackTrace(); // 異常捕捉處理,前面兩個處理環節的平常都能捕獲
            return 0;
        });

handle-任務完成或者異常時運行fn,返回值爲fn的返回

  • 相比exceptionally而言,便可處理上一環節的異常也能夠處理其正常返回值
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

whenComplete-任務完成或者異常時運行action,有返回值

  • whenComplete與handle的區別在於,它不參與返回結果的處理,把它當成監聽器便可
  • 即便異常被處理,在CompletableFuture外層,異常也會再次復現
  • 使用whenCompleteAsync時,返回結果則須要考慮多線程操做問題,畢竟會出現兩個線程同時操做一個結果
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

6 、多個任務的簡單組合

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

  • 使用示例
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。面試

Java後端開發三年多線程你都懂,問你異步編程你說你沒聽過???

歡迎你們一塊兒交流,喜歡文章記得關注我點贊喲,感謝支持!

相關文章
相關標籤/搜索