CompletableFuture的exceptionally

CompletableFuture的exceptionally


代码:

private void test() {
    System.out.println("开始...");

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

            // 此处故意抛出一个空指针异常。
            // 导致代码处理逻辑转入到exceptionally(new Function()
            if (true) {
                throw new NullPointerException();
            }

            System.out.println("返回 zhang");
            return "zhang";
        }
    }).exceptionally(new Function() {
        @Override
        public String apply(Throwable throwable) {
            System.out.println("exceptionally - apply " + throwable.toString());
            return "发生异常!";
        }
    }).whenCompleteAsync(new BiConsumer() {
        @Override
        public void accept(String s, Throwable throwable) {
            System.out.println("accept : " + s);
        }
    });

    System.out.println("运行至此.");
}


运行输出:

07-12 10:32:26.797 17266-17266/? I/System.out: 开始...
07-12 10:32:26.801 17266-17266/? I/System.out: 运行至此.
07-12 10:32:29.803 17266-17318/zhangphil.test I/System.out: exceptionally - apply :java.util.concurrent.CompletionException: java.lang.NullPointerException
07-12 10:32:29.805 17266-17318/zhangphil.test I/System.out: accept : 发生异常!

你可能感兴趣的:(Java,线程,多线程,Java多线程)