系列十四、异步回调

一、概述

系列十四、异步回调_第1张图片

二、案例代码

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/21 10:45
 * @Description: 异步任务案例代码
 */
public class CompletableFutureMainApp {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture future1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t future1");
        });
        System.out.println("future1.get() = " + future1.get());

        CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t future2");

            // int i = 10 / 0;

            return 1024;
        });
        Integer result = future2.whenComplete((t, u) -> {
            System.out.println("============>t:" + t);
            System.out.println("============>u:" + u);
        }).exceptionally(f -> {
            System.out.println("============>exception:" + f.getMessage());
            return 444;
        }).get();
        System.out.println("result = " + result);
    }

}

系列十四、异步回调_第2张图片

你可能感兴趣的:(JUC系列,JUC)