溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Java異步編程

發(fā)布時(shí)間:2021-10-20 10:30:45 來(lái)源:億速云 閱讀:102 作者:iii 欄目:編程語(yǔ)言

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

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 無(wú)返回值,輸出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返回

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

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

如何使用Java異步編程

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

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ù)完成則運(yùn)行action,依賴上一個(gè)任務(wù)的結(jié)果,無(wú)返回值

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ù)完成則運(yùn)行fn,依賴上一個(gè)任務(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ù)完成則運(yùn)行fn,依賴上一個(gè)任務(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)
  • 使用示例

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

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

如何使用Java異步編程

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

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

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

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

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

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

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

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

//第一個(gè)異步任務(wù),常量任務(wù)
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        //第二個(gè)異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三個(gè)任務(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í)行,誰(shuí)先執(zhí)行完則誰(shuí)觸發(fā)下一任務(wù)(二者選其最快)

如何使用Java異步編程

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

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

//第一個(gè)異步任務(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
        //第二個(gè)異步任務(wù)
        .supplyAsync(() ->{
            System.out.println("hello siting");
            return "hello siting";
        } , executor)
        //() ->  System.out.println("OK") 是第三個(gè)任務(wù)
        .runAfterEitherAsync(first, () ->  System.out.println("OK") , executor);
executor.shutdown();
--------輸出結(jié)果--------
hello siting
OK

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

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

//第一個(gè)異步任務(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
        //第二個(gè)異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三個(gè)任務(wù)
        .acceptEitherAsync(first, data ->  System.out.println(data) , executor);
executor.shutdown();
--------輸出結(jié)果--------
hello siting

上一個(gè)任務(wù)或者other任務(wù)完成, 運(yùn)行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)
  • 使用示例

//第一個(gè)異步任務(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
        //第二個(gè)異步任務(wù)
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三個(gè)任務(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é)有異常問(wèn)題,則會(huì)觸發(fā)exceptionally的調(diào)用相當(dāng)于 try...catch

  • 使用示例

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

handle-任務(wù)完成或者異常時(shí)運(yùn)行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ù)完成或者異常時(shí)運(yùn)行action,有返回值

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

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

  • 使用whenCompleteAsync時(shí),返回結(jié)果則需要考慮多線程操作問(wèn)題,畢竟會(huì)出現(xiàn)兩個(gè)線程同時(shí)操作一個(gè)結(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) -> {
            //異常捕捉處理, 但是異常還是會(huì)在外層復(fù)現(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 、多個(gè)任務(wù)的簡(jiǎn)單組合

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"));
//其中一個(gè)任務(wù)行完即可
future2.join();

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

// mayInterruptIfRunning 無(wú)影響;如果任務(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ù)未完成,則返回異常,需要對(duì)使用exceptionally,handle 對(duì)結(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()
//等待阻塞一段時(shí)間,并獲取返回值
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()
//強(qiáng)制地將返回值設(shè)置為value,無(wú)論該之前任務(wù)是否完成;類似complete
public void obtrudeValue(T value)
//強(qiáng)制地讓異常拋出,異常返回,無(wú)論該之前任務(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異步編程”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI