197、商城业务-异步-CompletableFuture-完成回调与异常感知

 public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main....start.....");
//        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//            System.out.println("当前线程:" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果:" + i);
//        }, executor);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程:" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果:" + i);
            return i;
        }, executor).whenComplete((res,excption) -> {
            // 虽然能得到异常信息,但是没法修改返回数据
            System.out.println("异步任务成功完成了...结果是:" + res + ";异常是:" + excption);
        }).exceptionally(throwable -> {
            //可以感知异常,同时返回默认值
            return 10;
        });
        Integer integer = future.get();
        System.out.println("main....end....." + integer);
    }

猜你喜欢

转载自blog.csdn.net/pyd1040201698/article/details/108433616