CompletableFuture的runAfterBothAsync

CompletableFuture的runAfterBothAsync


runAfterBothAsync:假设有两个线程A和B,这两个线程都是异步执行的,但是不确定A和B何时执行完毕,但是需要在A和B都执行完毕后运行线程C。

    private void test() {

        System.out.println("开始...");

        CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("返回 zhang");
                return "zhang";
            }
        }).runAfterBothAsync(CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("返回 phil");
                return "phil";
            }
        }), new Runnable() {
            @Override
            public void run() {
                System.out.println("开始 run");
            }
        });
    }



代码运行结果输出:

07-02 14:06:59.016 23450-23450/zhangphil.test I/System.out: 开始...
07-02 14:07:02.020 23450-23493/zhangphil.test I/System.out: 返回 zhang
07-02 14:07:04.021 23450-23494/zhangphil.test I/System.out: 返回 phil
    开始 run


线程返回“zhang”和"phil"后, 开始运行线程Runnable里面的线程体。注意返回“zhang”和“phil”的线程是同时执行的。

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/80883482