springboot简单异步任务Async

5 篇文章 0 订阅
5 篇文章 0 订阅

启动类 

@EnableAsync

异步任务 

 @Component 扫描组件

  @Async 告诉springboot 这是个异步任务

创建四个 异步任务   这里打印出异步执行时间

@Component
public class AsyncTask {
    @Async
    public Future<Boolean> myAsyncTask1()throws Exception{
        long startTime = System.currentTimeMillis();
        Thread.sleep(1000);
        long endTime = System.currentTimeMillis();
        System.out.println("任务①耗时"+(endTime-startTime)+"毫秒");
        return  new AsyncResult<>(true);
    }
    @Async
    public Future<Boolean> myAsyncTask2()throws Exception{
        long startTime = System.currentTimeMillis();
        Thread.sleep(1500);
        long endTime = System.currentTimeMillis();
        System.out.println("任务②耗时"+(endTime-startTime)+"毫秒");
        return  new AsyncResult<>(true);
    }
    @Async
    public Future<Boolean> myAsyncTask3()throws Exception{
        long startTime = System.currentTimeMillis();
        Thread.sleep(600);
        long endTime = System.currentTimeMillis();
        System.out.println("任务③耗时"+(endTime-startTime)+"毫秒");
        return  new AsyncResult<>(true);
    }
    @Async
    public Future<Boolean> myAsyncTask4()throws Exception{
        long startTime = System.currentTimeMillis();
        Thread.sleep(700);
        long endTime = System.currentTimeMillis();
        System.out.println("任务④耗时"+(endTime-startTime)+"毫秒");
        return  new AsyncResult<>(true);
    }
}

 调用

@RestController
@RequestMapping("/async")
public class AsyncController {

    @Autowired
    AsyncTask task;

    @RequestMapping("/myAsync")
    public String myAsync() throws Exception {
        StringBuffer buffer = new StringBuffer("异步执行任务总耗时为:");
        long startTime = System.currentTimeMillis();
        Future<Boolean> async1 = task.myAsyncTask1();
        Future<Boolean> async2 = task.myAsyncTask2();
        Future<Boolean> async3 = task.myAsyncTask3();
        Future<Boolean> async4 = task.myAsyncTask4();
        while (!async1.isDone() || !async2.isDone() ||
                !async3.isDone() || !async4.isDone()) {
            if (!async1.isDone() && !async2.isDone() && !async3.isDone() && !async4.isDone()) {
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        buffer.append((endTime - startTime));
        buffer.append("毫秒");
        System.out.println(buffer);
        return buffer.toString();
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值