java8 CompletableFuture,allOf多實例返回


 
https://www.jianshu.com/p/1db996cf7574
 
我們在處理業務時,有時會有多任務異步處理,同步返回結果的情況,在java中,我們可以使用CompletableFuture的allOf方法來實現多實例的同時返回。
   public void futureTest() { CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("future1 finished!"); return "future1 finished!"; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { System.out.println("future2 finished!"); return "future2 finished!"; }); CompletableFuture<Void> combindFuture = CompletableFuture.allOf(future1, future2); try { combindFuture.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("future1: " + future1.isDone() + " future2: " + future2.isDone()); } 

在這里我們可以將對各future實例添加到allOf方法中,然后通過future的get()方法獲取future的狀態。如果allOf里面的所有線程為執行完畢,主線程會阻塞,直到allOf里面的所有線程都執行,線程就會被喚醒。

異步編程,不想阻塞線程的話,可以使用thenAccpt、thenApply、thenRun,future結束后,執行異步方法



作者:nickbi
鏈接:https://www.jianshu.com/p/1db996cf7574
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM