Java CompletableFuture anyOf:线程队列只要有一个异步线程完成就触发(5)

Java CompletableFuture anyOf:线程队列只要有一个异步线程完成就触发(5)

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<Object> anyOf = CompletableFuture.anyOf(f1, f2);
        System.out.println("到这里了。");
    }

输出:

06-13 08:52:20.883 18385-18385/zhangphil.test I/System.out: 到这里了。
06-13 08:52:22.897 18385-18412/zhangphil.test I/System.out: 1528851142896:f2
06-13 08:52:23.894 18385-18411/zhangphil.test I/System.out: 1528851143893:f1

anyOf,只要异步线程队列有一个任务率先完成就返回,这个特性可以用来获取最快的那个线程结果。

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/80673805
今日推荐