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
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/toSeeMyDream/p/9824385.html