JUC系列十五:异步回调

1.1、原理

JUC系列十五:异步回调

1.2、实例

package com.atguigu.juc;

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() + "\t completableFuture1");
        });
        completableFuture1.get();

        //异步回调
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t completableFuture2");
            int i = 10 / 0;
            return 1024;
        });
        completableFuture2.whenComplete((t, u) -> {
            System.out.println("************t = " + t);
            System.out.println("************u = " + u);
        }).exceptionally(f -> {
            System.out.println("--------exception:" + f.getMessage());
            return 444;
        });
    }
}

JUC系列十五:异步回调
JUC系列十五:异步回调

上一篇:【工具类】CompletableFuture 使用详解


下一篇:CompletableFuture异步编排