JUC基础之异步回调

Future :对将来的某个事件结果进行建模


Future

CompletableFuture

异步任务

没有返回值的runAsync方法

public static void main(String[] args) throws ExecutionException, InterruptedException
{
    /*
    异步执行
    成功回调
    失败回调
     */
    //异步调用 发起一个请求
    CompletableFuture<Void> completableFuture =  CompletableFuture.runAsync(()->{
        System.out.println(Thread.currentThread().getName()+"runAsync");
    });
    System.out.println("Y1 ");
    //获取阻塞结果
    completableFuture.get();
}
运行结果:
Y1 
ForkJoinPool.commonPool-worker-1runAsync

程序往下执行的时候没有先打印
System.out.println(Thread.currentThread().getName()+"runAsync”);
先输出了 Y1 后主线程到get,回调了System.out.println(Thread.currentThread().getName()+"runAsync”);

有返回值的supplyAsync方法

//有返回值的异步回调
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
    System.out.println("supplyAsync=>Integer");
    return 111;
});

回调异步请求

//打印返回值
System.out.println(
        completableFuture.whenComplete((t, u) -> { //成功时的回调
             System.out.println("t:" + t);   //输出看看t是什么
             System.out.println("u:" + u);  //输出看看u是什么
}).exceptionally((e) -> {  //失败时的回调
    e.getMessage();  //打印异常信息
    return 400;       //失败返回
}).get());

运行结果:
supplyAsync=>Integer
t:200
u:null
200

正常运行没有返回400,返回了200
t:代表正常的返回结果
u:没有异常时是null,错误了就是错误信息

whenComplete() 和 exceptionally() 的参数是一个函数式接口 可以看我之前写的四大函数式接口

@FunctionalInterface
public interface BiConsumer<T, U> {
    /**
     * Performs this operation on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     */
    void accept(T t, U u);


@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

制造一个错误看看会不会返回400

CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
    System.out.println("supplyAsync=>Integer");
    int i = 1/0;  //制造错我
    return 200;
});
//打印返回值
System.out.println(
        completableFuture.whenComplete((t, u) -> {     //成功时的回调
             System.out.println("t:" + t);   //输出看看t是什么
             System.out.println("u:" + u);  //输出看看u是什么
}).exceptionally((e) -> {  //失败时的回调
    e.getMessage();  //打印异常信息
    return 400;       //失败返回
}).get());

运行结果:
supplyAsync=>Integer
t:null
u:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
400

返回了400,并且t为null表示没有正常返回结果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。