第13章 异步回调

 

 同步:我去教室找张三,张三不在座位上,我就在座位上等张三回来

 异步:我去教室找张三,张三不在座位上,我就让旁边同学等张三回来就通知我,这个时候我可以去做其他事情

package JUC.completable;

import java.util.concurrent.CompletableFuture;

public class CompletableFutureDemo {

    public static void main(String[] args) throws Exception {
        //异步调用 没有返回值
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"completableFuture1");
        });
        completableFuture1.get();

        //异步调用 有返回值
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"completableFuture2");
//            int i = 1/0;
            return 1024;
        });
        completableFuture2.whenComplete((t,u) -> {
            System.out.println("---t="+t);//返回值
            System.out.println("---u="+u);//异常信息
        }).get();

    }
}

 

posted @ 2022-05-03 23:38  狂热搬砖家  阅读(24)  评论(0)    收藏  举报