這篇文章主要介紹“如何使用Java異步編程”,在日常操作中,相信很多人在如何使用Java異步編程問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”如何使用Java異步編程”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
隆回網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。成都創(chuàng)新互聯(lián)從2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
//使用內(nèi)置線程ForkJoinPool.commonPool(),根據(jù)supplier構(gòu)建執(zhí)行任務(wù) public static CompletableFuture supplyAsync(Supplier supplier) //指定自定義線程,根據(jù)supplier構(gòu)建執(zhí)行任務(wù) public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
//使用內(nèi)置線程ForkJoinPool.commonPool(),根據(jù)runnable構(gòu)建執(zhí)行任務(wù) public static CompletableFuturerunAsync(Runnable runnable) //指定自定義線程,根據(jù)runnable構(gòu)建執(zhí)行任務(wù) public static CompletableFuture runAsync(Runnable runnable, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturerFuture = CompletableFuture .runAsync(() -> System.out.println("hello siting"), executor); //supplyAsync的使用 CompletableFuture 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
//有時(shí)候是需要構(gòu)建一個(gè)常量的CompletableFuture public static CompletableFuture completedFuture(U value)
任務(wù)完成則運(yùn)行action,不關(guān)心上一個(gè)任務(wù)的結(jié)果,無返回值
public CompletableFuturethenRun(Runnable action) public CompletableFuture thenRunAsync(Runnable action) public CompletableFuture thenRunAsync(Runnable action, Executor executor)
使用示例
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenRunAsync(() -> System.out.println("OK"), executor); executor.shutdown(); --------輸出結(jié)果-------- OK
public CompletableFuturethenAccept(Consumer super T> action) public CompletableFuture thenAcceptAsync(Consumer super T> action) public CompletableFuture thenAcceptAsync(Consumer super T> action, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenAcceptAsync(System.out::println, executor); executor.shutdown(); --------輸出結(jié)果-------- hello siting
public CompletableFuture thenApply(Function super T,? extends U> fn) public CompletableFuture thenApplyAsync(Function super T,? extends U> fn) public CompletableFuture thenApplyAsync(Function super T,? extends U> fn, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturefuture = 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
類似thenApply(區(qū)別是thenCompose的返回值是CompletionStage,thenApply則是返回 U),提供該方法為了和其他CompletableFuture任務(wù)更好地配套組合使用
public CompletableFuture thenCompose(Function super T, ? extends CompletionStage> fn) public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage> fn) public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage> fn, Executor executor)
使用示例
//第一個(gè)異步任務(wù),常量任務(wù) CompletableFuturef = CompletableFuture.completedFuture("OK"); //第二個(gè)異步任務(wù) ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFuturerunAfterBoth(CompletionStage> other, Runnable action) public CompletableFuture runAfterBothAsync(CompletionStage> other, Runnable action) public CompletableFuture runAfterBothAsync(CompletionStage> other, Runnable action, Executor executor)
使用示例
//第一個(gè)異步任務(wù),常量任務(wù) CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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è)任務(wù)完成再運(yùn)行other,fn再依賴消費(fèi)兩個(gè)任務(wù)的結(jié)果,無返回值 public CompletableFuturethenAcceptBoth(CompletionStage extends U> other, BiConsumer super T, ? super U> action) //兩個(gè)任務(wù)異步完成,fn再依賴消費(fèi)兩個(gè)任務(wù)的結(jié)果,無返回值 public CompletableFuture thenAcceptBothAsync(CompletionStage extends U> other, BiConsumer super T, ? super U> action) //兩個(gè)任務(wù)異步完成(第二個(gè)任務(wù)用指定線程池執(zhí)行),fn再依賴消費(fèi)兩個(gè)任務(wù)的結(jié)果,無返回值 public CompletableFuture thenAcceptBothAsync(CompletionStage extends U> other, BiConsumer super T, ? super U> action, Executor executor)
使用示例
//第一個(gè)異步任務(wù),常量任務(wù) CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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è)任務(wù)完成再運(yùn)行other,fn再依賴消費(fèi)兩個(gè)任務(wù)的結(jié)果,有返回值 public CompletableFuturethenCombine(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn) //兩個(gè)任務(wù)異步完成,fn再依賴消費(fèi)兩個(gè)任務(wù)的結(jié)果,有返回值 public CompletableFuture 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 CompletableFuture thenCombineAsync(CompletionStage extends U> other, BiFunction super T,? super U,? extends V> fn, Executor executor)
使用示例
//第一個(gè)異步任務(wù),常量任務(wù) CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFuturerunAfterEither(CompletionStage> other, Runnable action) public CompletableFuture runAfterEitherAsync(CompletionStage> other, Runnable action) public CompletableFuture runAfterEitherAsync(CompletionStage> other, Runnable action, Executor executor)
使用示例
//第一個(gè)異步任務(wù),休眠1秒,保證最晚執(zhí)行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} System.out.println("hello world"); return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFutureacceptEither(CompletionStage extends T> other, Consumer super T> action) public CompletableFuture acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action, Executor executor) public CompletableFuture acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action, Executor executor)
使用示例
//第一個(gè)異步任務(wù),休眠1秒,保證最晚執(zhí)行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFuture applyToEither(CompletionStage extends T> other, Function super T, U> fn) public CompletableFuture applyToEitherAsync(CompletionStage extends T> other, Function super T, U> fn) public CompletableFuture applyToEitherAsync(CompletionStage extends T> other, Function super T, U> fn, Executor executor)
使用示例
//第一個(gè)異步任務(wù),休眠1秒,保證最晚執(zhí)行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFutureexceptionally(Function fn)
如果之前的處理環(huán)節(jié)有異常問題,則會(huì)觸發(fā)exceptionally的調(diào)用相當(dāng)于 try...catch
使用示例
CompletableFuturefirst = 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; });
相比exceptionally而言,即可處理上一環(huán)節(jié)的異常也可以處理其正常返回值
public CompletableFuture handle(BiFunction super T, Throwable, ? extends U> fn) public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U> fn) public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U> fn, Executor executor)
使用示例
CompletableFuturefirst = 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與handle的區(qū)別在于,它不參與返回結(jié)果的處理,把它當(dāng)成監(jiān)聽器即可
即使異常被處理,在CompletableFuture外層,異常也會(huì)再次復(fù)現(xiàn)
使用whenCompleteAsync時(shí),返回結(jié)果則需要考慮多線程操作問題,畢竟會(huì)出現(xiàn)兩個(gè)線程同時(shí)操作一個(gè)結(jié)果
public CompletableFuturewhenComplete(BiConsumer super T, ? super Throwable> action) public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable> action) public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable> action, Executor executor)
使用示例
CompletableFuturefirst = 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
public static CompletableFutureallOf(CompletableFuture>... cfs) public static CompletableFuture
使用示例
CompletableFuturefuture = CompletableFuture .allOf(CompletableFuture.completedFuture("A"), CompletableFuture.completedFuture("B")); //全部任務(wù)都需要執(zhí)行完 future.join(); CompletableFuture
// mayInterruptIfRunning 無影響;如果任務(wù)未完成,則返回異常 public boolean cancel(boolean mayInterruptIfRunning) //任務(wù)是否取消 public boolean isCancelled()
使用示例
CompletableFuturefuture = 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
// 任務(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ù)是否完成;類似complete public void obtrudeValue(T value) //強(qiáng)制地讓異常拋出,異常返回,無論該之前任務(wù)是否完成;類似completeExceptionally public void obtrudeException(Throwable ex)
使用示例
CompletableFuturefuture = 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)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!