Springboot 注解@Async 异步线程 简单使用

需要导入的包

import org.springframework.scheduling.annotation.Async;
import java.util.concurrent.Future;

举一个小例子 计算一个方法执行所需要的时间  超时结束请求该方法

1、以下的方法是需要计算执行时间的  在这个方法上加上@Async 这个注解,并且返回的类型一定是Future<>,尖括号中间放自己所需要返回的值得类型,这里是一个map

    @Async
    public Future> chaxun(String mobile) throws Exception {
        return new AsyncResult<>(Ip138Util.chaxun(mobile));
    }

2、调用该方法 (这里没有定义一个完整的方法 ,只展示如何调用的部分)

Map map = null;
//当前系统时间
long begin = System.currentTimeMillis();
Future> onlineFutrue = ip138Service.chaxun(mobile);
//写一个死循环 进行线程的调用
while (true) {
    //判断方法执行是否超过了300毫秒 如果超过break
    if ((System.currentTimeMillis() - begin) >= 300) {
          break;
     }
    //onlineFutrue.isDone() 表示方法执行结束
    if (map == null && onlineFutrue.isDone()) {
        //获取到我们原本需要的数据 返回后break
        map = onlineFutrue.get();
         break;
     }
}

 

你可能感兴趣的:(springboot注解)