JUC个人学习笔记13---异步回调

根据b站UP主狂神说JUC课程所写的个人学习笔记

视频地址:https://www.bilibili.com/video/BV1B7411L7tE?from=search&seid=14761503393031794075


Future设计的初衷是对将来的某个事件建模 

JUC个人学习笔记13---异步回调

//异步调用: CompletableFuture
//成功回调
//失败回调
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        //没有返回值的runAsync异步回调
//        //发起一个请求
//        CompletableFuture <Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
//        });
//        System.out.println("1111");
//
//
//completableFuture.get();//阻塞获取执行结果
        //有返回值的异步回调
        //失败返回错误信息
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"Integer");
            int i = 10/0;

            return 1024;
        });
        System.out.println(integerCompletableFuture.whenComplete((t, u) -> {
            System.out.println("t" + t);//正常的返回结果
            System.out.println("u" + u);//错误信息
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());//可以返回错误信息
            return 233;
        }).get());
    }
}