JUC-CompletableFuture异步回调

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

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

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

        //有返回值异步回调 supplyAsync
        CompletableFuture<Integer> 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);
    }
}

你可能感兴趣的:(Java,java)