如何使用Java異步編程

這篇文章主要介紹“如何使用Java異步編程”,在日常操作中,相信很多人在如何使用Java異步編程問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用Java異步編程”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

隆回網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項目制作,到程序開發(fā),運營維護。成都創(chuàng)新互聯(lián)從2013年成立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。

1、創(chuàng)建異步線程任務(wù)

根據(jù)supplier創(chuàng)建CompletableFuture任務(wù)

//使用內(nèi)置線程ForkJoinPool.commonPool(),根據(jù)supplier構(gòu)建執(zhí)行任務(wù)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//指定自定義線程,根據(jù)supplier構(gòu)建執(zhí)行任務(wù)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

根據(jù)runnable創(chuàng)建CompletableFuture任務(wù)

//使用內(nèi)置線程ForkJoinPool.commonPool(),根據(jù)runnable構(gòu)建執(zhí)行任務(wù)
public static CompletableFuture<Void> runAsync(Runnable runnable)
//指定自定義線程,根據(jù)runnable構(gòu)建執(zhí)行任務(wù)
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(); // 線程池需要關(guān)閉
--------輸出結(jié)果--------
hello siting
null
hello siting

常量值作為CompletableFuture返回

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

2 、線程串行執(zhí)行

如何使用Java異步編程

任務(wù)完成則運行action,不關(guān)心上一個任務(wù)的結(jié)果,無返回值

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();
--------輸出結(jié)果--------
OK

任務(wù)完成則運行action,依賴上一個任務(wù)的結(jié)果,無返回值

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();
--------輸出結(jié)果--------
hello siting

任務(wù)完成則運行fn,依賴上一個任務(wù)的結(jié)果,有返回值

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();
--------輸出結(jié)果--------
hello world
OK

thenCompose - 任務(wù)完成則運行fn,依賴上一個任務(wù)的結(jié)果,有返回值

  • 類似thenApply(區(qū)別是thenCompose的返回值是CompletionStage,thenApply則是返回 U),提供該方法為了和其他CompletableFuture任務(wù)更好地配套組合使用

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)
  • 使用示例

//第一個異步任務(wù),常量任務(wù)
CompletableFuture<String> f = CompletableFuture.completedFuture("OK");
//第二個異步任務(wù)
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello world", executor)
        .thenComposeAsync(data -> {
            System.out.println(data); return f; //使用第一個任務(wù)作為返回
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------輸出結(jié)果--------
hello world
OK

3 、線程并行執(zhí)行

如何使用Java異步編程

兩個CompletableFuture[并行]執(zhí)行完,然后執(zhí)行action,不依賴上兩個任務(wù)的結(jié)果,無返回值

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)
  • 使用示例

//第一個異步任務(wù),常量任務(wù)
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        //第二個異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // () -> System.out.println("OK") 是第三個任務(wù)
        .runAfterBothAsync(first, () -> System.out.println("OK"), executor);
executor.shutdown();
--------輸出結(jié)果--------
OK

兩個CompletableFuture[并行]執(zhí)行完,然后執(zhí)行action,依賴上兩個任務(wù)的結(jié)果,無返回值

//第一個任務(wù)完成再運行other,fn再依賴消費兩個任務(wù)的結(jié)果,無返回值
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)
//兩個任務(wù)異步完成,fn再依賴消費兩個任務(wù)的結(jié)果,無返回值     
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)  
//兩個任務(wù)異步完成(第二個任務(wù)用指定線程池執(zhí)行),fn再依賴消費兩個任務(wù)的結(jié)果,無返回值                
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action, Executor executor)
  • 使用示例

//第一個異步任務(wù),常量任務(wù)
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        //第二個異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三個任務(wù)
        .thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor);
executor.shutdown();
--------輸出結(jié)果--------
hello siting

兩個CompletableFuture[并行]執(zhí)行完,然后執(zhí)行action,依賴上兩個任務(wù)的結(jié)果,有返回值

//第一個任務(wù)完成再運行other,fn再依賴消費兩個任務(wù)的結(jié)果,有返回值
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, 
  BiFunction<? super T,? super U,? extends V> fn)
//兩個任務(wù)異步完成,fn再依賴消費兩個任務(wù)的結(jié)果,有返回值
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn)   
//兩個任務(wù)異步完成(第二個任務(wù)用指定線程池執(zhí)行),fn再依賴消費兩個任務(wù)的結(jié)果,有返回值        
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn, Executor executor)
  • 使用示例

//第一個異步任務(wù),常量任務(wù)
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        //第二個異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三個任務(wù)
        .thenCombineAsync(first, (s, w) -> {
            System.out.println(s);
            return "OK";
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------輸出結(jié)果--------
hello siting
OK

4 、線程并行執(zhí)行,誰先執(zhí)行完則誰觸發(fā)下一任務(wù)(二者選其最快)

如何使用Java異步編程

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

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)
  • 使用示例

//第一個異步任務(wù),休眠1秒,保證最晚執(zhí)行晚
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
        //第二個異步任務(wù)
        .supplyAsync(() ->{
            System.out.println("hello siting");
            return "hello siting";
        } , executor)
        //() ->  System.out.println("OK") 是第三個任務(wù)
        .runAfterEitherAsync(first, () ->  System.out.println("OK") , executor);
executor.shutdown();
--------輸出結(jié)果--------
hello siting
OK

上一個任務(wù)或者other任務(wù)完成, 運行action,依賴最先完成任務(wù)的結(jié)果,無返回值

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)
  • 使用示例

//第一個異步任務(wù),休眠1秒,保證最晚執(zhí)行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        //第二個異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三個任務(wù)
        .acceptEitherAsync(first, data ->  System.out.println(data) , executor);
executor.shutdown();
--------輸出結(jié)果--------
hello siting

上一個任務(wù)或者other任務(wù)完成, 運行fn,依賴最先完成任務(wù)的結(jié)果,有返回值

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)
  • 使用示例

//第一個異步任務(wù),休眠1秒,保證最晚執(zhí)行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        //第二個異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三個任務(wù)
        .applyToEitherAsync(first, data ->  {
            System.out.println(data);
            return "OK";
        } , executor);
System.out.println(future);
executor.shutdown();
--------輸出結(jié)果--------
hello siting
OK

5 、處理任務(wù)結(jié)果或者異常

exceptionally-處理異常

如何使用Java異步編程

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
  • 如果之前的處理環(huán)節(jié)有異常問題,則會觸發(fā)exceptionally的調(diào)用相當于 try...catch

  • 使用示例

CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("main error!");
            }
            return "hello world";
        })
        .thenApply(data -> 1)
        .exceptionally(e -> {
            e.printStackTrace(); // 異常捕捉處理,前面兩個處理環(huán)節(jié)的日常都能捕獲
            return 0;
        });

handle-任務(wù)完成或者異常時運行fn,返回值為fn的返回

  • 相比exceptionally而言,即可處理上一環(huán)節(jié)的異常也可以處理其正常返回值

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());
--------輸出結(jié)果--------
java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
 ... 5 more
null

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

  • whenComplete與handle的區(qū)別在于,它不參與返回結(jié)果的處理,把它當成監(jiān)聽器即可

  • 即使異常被處理,在CompletableFuture外層,異常也會再次復現(xiàn)

  • 使用whenCompleteAsync時,返回結(jié)果則需要考慮多線程操作問題,畢竟會出現(xiàn)兩個線程同時操作一個結(jié)果

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) -> {
            //異常捕捉處理, 但是異常還是會在外層復現(xiàn)
            System.out.println(e.getMessage());
        });
first.join();
--------輸出結(jié)果--------
java.lang.RuntimeException: main error!
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
 ... 5 more

6 、多個任務(wù)的簡單組合

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"));
//全部任務(wù)都需要執(zhí)行完
future.join();
CompletableFuture<Object> future2 = CompletableFuture
        .anyOf(CompletableFuture.completedFuture("C"),
                CompletableFuture.completedFuture("D"));
//其中一個任務(wù)行完即可
future2.join();

7、取消執(zhí)行線程任務(wù)

// mayInterruptIfRunning 無影響;如果任務(wù)未完成,則返回異常
public boolean cancel(boolean mayInterruptIfRunning) 
//任務(wù)是否取消
public boolean isCancelled()
  • 使用示例

CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> {
            try { Thread.sleep(1000);  } catch (Exception e) { }
            return "hello world";
        })
        .thenApply(data -> 1);

System.out.println("任務(wù)取消前:" + future.isCancelled());
// 如果任務(wù)未完成,則返回異常,需要對使用exceptionally,handle 對結(jié)果處理
future.cancel(true);
System.out.println("任務(wù)取消后:" + future.isCancelled());
future = future.exceptionally(e -> {
    e.printStackTrace();
    return 0;
});
System.out.println(future.join());
--------輸出結(jié)果--------
任務(wù)取消前:false
任務(wù)取消后:true
java.util.concurrent.CancellationException
 at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276)
 at Test.main(Test.java:25)
0

8、任務(wù)的獲取和完成與否判斷

// 任務(wù)是否執(zhí)行完成
public boolean isDone()
//阻塞等待 獲取返回值
public T join()
// 阻塞等待 獲取返回值,區(qū)別是get需要返回受檢異常
public T get()
//等待阻塞一段時間,并獲取返回值
public T get(long timeout, TimeUnit unit)
//未完成則返回指定value
public T getNow(T valueIfAbsent)
//未完成,使用value作為任務(wù)執(zhí)行的結(jié)果,任務(wù)結(jié)束。需要future.get獲取
public boolean complete(T value)
//未完成,則是異常調(diào)用,返回異常結(jié)果,任務(wù)結(jié)束
public boolean completeExceptionally(Throwable ex)
//判斷任務(wù)是否因發(fā)生異常結(jié)束的
public boolean isCompletedExceptionally()
//強制地將返回值設(shè)置為value,無論該之前任務(wù)是否完成;類似complete
public void obtrudeValue(T value)
//強制地讓異常拋出,異常返回,無論該之前任務(wù)是否完成;類似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("任務(wù)完成前:" + future.isDone());
future.complete(10);
System.out.println("任務(wù)完成后:" + future.join());
--------輸出結(jié)果--------
任務(wù)完成前:false
任務(wù)完成后:10

到此,關(guān)于“如何使用Java異步編程”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

分享題目:如何使用Java異步編程
URL網(wǎng)址:http://bm7419.com/article20/jcejco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司網(wǎng)站維護、網(wǎng)站營銷、微信公眾號、網(wǎng)站設(shè)計做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管