springboot主线程_异步调用实现多线程处理任务 | 带你读《SpringBoot实战教程》之十四-阿里云开发者社区...

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。

21.异步调用:

在项目中,当访问其它接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行,我们可以使用多线程来并行的处理任务,SpringBoot提供了异步处理方式@Async。

编写AsyncService:

public interface AsyncService {

Future doTask1()throws Exception;

Future doTask2()throws Exception;

Future doTask3()throws Exception;

}

编写AsyncServiceImpl:

@Service

public class AsyncServiceImpl implements AsyncService {

public static Random random =new Random();

@Async

@Override

public Future doTask1() throws Exception {

System.out.println("开始做任务一");

long start = System.currentTimeMillis();

Thread.sleep(random.nextInt(10000));

long end = System.currentTimeMillis();

System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");

return new AsyncResult<>("任务一完成");

}

@Async

@Override

public Future doTask2()throws Exception {

System.out.println("开始做任务二");

long start = System.currentTimeMillis();

Thread.sleep(random.nextInt(10000));

long end = System.currentTimeMillis();

System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");

return new AsyncResult<>("任务二完成");

}

@Async

@Override

public Future doTask3() throws Exception{

System.out.println("开始做任务三");

long start = System.currentTimeMillis();

Thread.sleep(random.nextInt(10000));

long end = System.currentTimeMillis();

System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");

return new AsyncResult<>("任务三完成");

}

}

在Controller中调用service功能:

@Controller

public class TestController {

@Autowired

private AsyncService asyncService;

@RequestMapping("/async")

@ResponseBody

public String getEntityById() throws Exception {

long start = System.currentTimeMillis();

Future task1 = asyncService.doTask1();

Future task2 = asyncService.doTask2();

Future task3 = asyncService.doTask3();

while(true) {

if(task1.isDone() && task2.isDone() && task3.isDone()) {

// 三个任务都调用完成,退出循环等待

break;

}

Thread.sleep(1000);

}

long end = System.currentTimeMillis();

return "任务全部完成,总耗时:" + (end - start) + "毫秒";

}

}

要是使用异步的话,还需启动类中开始异步执行。

在启动类上加入@EnableAsync注解。

执行的结果为:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值