SpringBoot2.x异步任务Future

异步任务创建见上一章 链接

异步任务Future获取结果

注意:
要把异步任务封装到类里面,不能直接写到Controller
增加Future 返回结果 AsyncResult(“task执行完成”);
如果需要拿到结果 需要判断全部的 task.isDone()

代码:

AsyncTask

@Component
@Async
public class AsyncTask {
    //泛型里面填写自己想要返回的数据类型
    //AsyncResult用于封装异步任务的结果
    public Future<String> task4(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task4");
        return new AsyncResult<String>("  task4");
    }

    public Future<String> task5(){
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task5");
        return new AsyncResult<String>("  task5");
    }
}

测试方法:

 @Autowired
    private AsyncTask asyncTask;

    @GetMapping("async")
    public JsonData testAsync(){
        long begin=System.currentTimeMillis();
        
        Future<String> task4=asyncTask.task4();
        Future<String> task5=asyncTask.task5();

        for (;;){
            if (task4.isDone()&&task5.isDone()){
                String task4Result= null;
                String task5Result= null;
                try {
                    task4Result = task4.get();
                    System.out.println(task4Result);
                    task5Result=task5.get();
                    System.out.println(task5Result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }finally {
                    break;
                }
            }
        }

        long end=System.currentTimeMillis();
        return JsonData.buildSuccess(end-begin);
    }

在这里插入图片描述

测试结果:

在这里插入图片描述
如果不是异步执行则需要8秒

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值