1.开启异步调用任务:在启动类加上@EnableAsync,表示开启异步调用任务
2.创建异步调用任务类:和定时任务相同的地方是任务类须加上@Component,不同的是异步调用的方法须加上@Async表示是异步任务
@Component
public class AsyncTasks {
@Async
public Future<Boolean> doTask1() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(1000);
long end=System.currentTimeMillis();
System.out.println("Task1耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
@Async
public Future<Boolean> doTask2() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(700);
long end=System.currentTimeMillis();
System.out.println("Task2耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
@Async
public Future<Boolean> doTask3() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(600);
long end=System.currentTimeMillis();
System.out.println("Task3耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
public class AsyncTasks {
@Async
public Future<Boolean> doTask1() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(1000);
long end=System.currentTimeMillis();
System.out.println("Task1耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
@Async
public Future<Boolean> doTask2() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(700);
long end=System.currentTimeMillis();
System.out.println("Task2耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
@Async
public Future<Boolean> doTask3() throws Exception{
long start=System.currentTimeMillis();
Thread.sleep(600);
long end=System.currentTimeMillis();
System.out.println("Task3耗时:"+(end-start)+"毫秒!");
return new AsyncResult<Boolean>(true);
}
}
3.创建异步调用的Controller
注意:本例中有三个异步任务,需要保证每个异步任务都执行完毕!
4.本例中的三个异步任务,执行时间分别是1000ms/700ms/600ms,如果是同步执行则总时间应该是2300ms,异步执行时间理论上应该是最大时间1000ms,但是由于有个while循环,所以时间应该略大于1000ms!
进入浏览器访问http://localhost:8088/SpringBoot/asy/test
以上结果与LZ分析基本一致!