什么是异步调用:
异步调用对应的是同步调用,同步调用指程序按照定义的顺序一次执行,每一行程序都必须等待上一行程序执行完成之后才能执行;异步调用指程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序
在spring boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步
/** * 定义3个任务 * @author Angel(QQ:412887952) * @version v.0.1 */ @Component publicclass Task2 { //定义一个随机对象. publicstatic Random random =new Random(); //任务一; @Async publicvoid doTaskOne() throws Exception { System.out.println("开始做任务一"); longstart = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); longend = System.currentTimeMillis(); System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); } //任务二; @Async publicvoid doTaskTwo() throws Exception { System.out.println("开始做任务二"); longstart = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); longend = System.currentTimeMillis(); System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); } //任务3; @Async publicvoid doTaskThree() throws Exception { System.out.println("开始做任务三"); longstart = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); longend = System.currentTimeMillis(); System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); } }
为了让@Async注解能够生效,还需要在spring boot启动类中配置@EnableAsync
评论