SpringBoot2.x异步任务

1.启动类里面使用@EnableAsync注解开启功能,自动扫描

 

2.在方法上面加上@Async

 

我这里写了一个测试类

@Component
@Async
public class AsyncTask {
    public void task1() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务1耗时:"+total);
    }

    public void task2() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(2000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务2耗时:"+total);
    }

    public void task3() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        long total = end - begin;
        System.err.println("任务3耗时:"+total);
    }
public Future<String> task4() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(3000);
    long end = System.currentTimeMillis();
    long total = end - begin;
    System.err.println("任务4耗时:"+total);
    return  new AsyncResult<String>("任务4");
}
}

 

然后在controller 加入一个方法调用这个异步的方法任务

/*
* 异步任务
* */
@GetMapping("async_total")
public long AsyncTotal() throws InterruptedException {
    long begin  = System.currentTimeMillis();
    asyncTask.task1();
    asyncTask.task2();
    asyncTask.task3();
Future<String> task4 =  asyncTask.task4();
if(task4.isDone()){
    System.err.println("------>返回成功");
    break;
}
    long end = System.currentTimeMillis();
    long counttotal = end - begin;
    return counttotal;
}

如果为同步这里我们最少需要花费6秒因为我三个任务一起等待了6秒

但是我使用了异步我请求这个只花费了2秒钟

 

task4  这是有返回类型的就是得到此次调用的返回  并用isDone 判断是否有返回 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值