1. 程式人生 > >Java CompletableFuture:allOf等待所有非同步執行緒任務結束

Java CompletableFuture:allOf等待所有非同步執行緒任務結束

   private void method() throws ExecutionException, InterruptedException {
        CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            
return "f1"; }); f1.whenCompleteAsync(new BiConsumer<String, Throwable>() { @Override public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); CompletableFuture
<String> f2 = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } return "f2"; }); f2.whenCompleteAsync(new BiConsumer<String, Throwable>() { @Override
public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2); //阻塞,直到所有任務結束。 System.out.println(System.currentTimeMillis() + ":阻塞"); all.join(); System.out.println(System.currentTimeMillis() + ":阻塞結束"); //一個需要耗時2秒,一個需要耗時3秒,只有當最長的耗時3秒的完成後,才會結束。 System.out.println("任務均已完成。"); }

輸出:

06-12 20:16:37.400 31142-31142/zhangphil.test I/System.out: 1528805797400:阻塞
06-12 20:16:39.406 31142-31171/zhangphil.test I/System.out: 1528805799406:f2
06-12 20:16:40.404 31142-31170/zhangphil.test I/System.out: 1528805800404:f1
06-12 20:16:40.404 31142-31142/zhangphil.test I/System.out: 1528805800404:阻塞結束
任務均已完成。


可以看到f2很快就返回,是因為f2僅耗時2秒。f1需要耗時3秒,因此在f2結束後一秒,f1也返回。此時才執行join後的程式碼。
---------------------
作者:zhangphil
來源:CSDN
原文:https://blog.csdn.net/zhangphil/article/details/80670593?utm_source=copy
版權宣告:本文為博主原創文章,轉載請附上博文連結!