异步回调,用一个例子带你起飞!

1.Future接口
Future 设计的初衷: 对将来的某个事件的结果进行建模

异步回调:
在这里插入图片描述

在这里插入图片描述
这里基本不怎么直接使用future,而是使用它的一个实现类CompletableFuture,这个类的很多方法都是加强了的,比较怕常用。
2.CompletableFuture类

在这里插入图片描述

接下俩就让我们用一个小例子来看看这个类是怎么来操作异步回调的吧
3.简单代码实现

*没有返回值的情况:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @program: juc
 * @description
 * @author: 不会编程的派大星
 * @create: 2021-04-27 20:56
 **/
public class CompletableFutureTask1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(4);  //这里用延迟一个任务锁需要花费的时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 我不需要返回结果");
        });

        System.out.println("hello "); 

        completableFuture.get(); //获取异步后的结果 -- 回调

    }
}

执行结果:
在这里插入图片描述
注:这里即使completableFuture的执行体在打印hello这行代码的前面,但依旧是先打印hello,再回调得到异步的结果
这里就好比 小明在未来的30分钟类要买水和上厕所 ,但是他已经憋不住了,于是乎他让小红去帮他买水,然后他去上厕所先,等上完厕所,他在喊小红把买的水给他,这样就节省了时间,提升了做事效率。

*需要返回结果的情况,成功时和失败时返回

import java.util.concurrent.CompletableFuture;

/**
 * @program: juc
 * @description
 * @author: 不会编程的派大星
 * @create: 2021-04-27 21:14
 **/
public class CompletableFutureTask {

    public static void main(String[] args) {

        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
          //错误时返回
            //int i = 10 /0;
            return 1024;
        });

        completableFuture.whenComplete((u,t) -> {
            System.out.println("u--->"+u);
            System.out.println("t--->"+t);
        }).exceptionally((e) -> {
            e.getMessage();
            return 200;
        });


    }
}

成功时返回:
whenComplete方法,可以看出里面所传的参数为BiConsumer 需要传 t和u两个参数:

在这里插入图片描述

执行结果:
在这里插入图片描述

失败时返回:
在这里插入图片描述

注:这里可以看出 u 和 t两个参数,一个是返回成功的结果,而另一个则是返回时的结果,正确和错误时,都可以拿到!

这次的讨论就到这里,欢迎留言讨论!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值