JUC-CompletableFuture异步回调

JUC-CompletableFuture异步回调,第1张

JUC-CompletableFuture异步回调
1.无返回值的 runAsync 异步回调
2.有返回值的 supplyAsync 异步回调

public class CompletableFuture_ {
    public static void main(String[] args) throws Exception {

        //没有返回值的异步回调 runAsync()
        CompletableFuture completableFuture1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " runAsync => Void");
        });
        System.out.println("无返回值:" + completableFuture1.get());

        //有返回值异步回调 supplyAsync
        CompletableFuture completableFuture2 =
                CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName() + " supplyAsync => Integer");
                    //int i = 10 / 0;
                    return 200;
                });

        Integer result = completableFuture2.whenComplete((t, u) -> {
            System.out.println("t=>" + t); //返回结果
            System.out.println("u=>" + u); //异常信息
        }).exceptionally((e) -> { //异常回调
            System.out.println("异常:" + e.getMessage());
            return 404;
        }).get();
        System.out.println("result=" + result);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5683842.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存