1、在启动类里面使用@EnableAsync注解开启功能,自动扫描
@SpringBootApplication
@EnableAsync //开启多任务
public class XdclassApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(XdclassApplication.class, args);
}
}
2、封装异步任务类,不能直接写到Controller中
@Async //加在类中某个方法前,代表某个方法是异步任务,加在类前,代表类中所有任务都是异步任务
@Component //交给spring容器管理,自动扫描
public class AsyncTask {
public void task1() throws InterruptedException {
Long start=System.currentTimeMillis();
Thread.sleep(1000L);
Long end=System.currentTimeMillis();
System.out.println("task1总用时"+(end-start));
}
public void task2() throws InterruptedException {
Long start=System.currentTimeMillis();
Thread.sleep(2000L);
Long end=System.currentTimeMillis();
System.out.println("task2总用时"+(end-start));
}
public void task3() throws InterruptedException {
Long start=System.currentTimeMillis();
Thread.sleep(3000L);
Long end=System.currentTimeMillis();
System.out.println("task3总用时"+(end-start));
}
//获取异步结果
public Future<String> task4() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
long end = System.currentTimeMillis();
System.out.println("任务4耗时="+(end-begin));
return new AsyncResult<String>("任务4");
}
public Future<String> task5() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(3000L);
long end = System.currentTimeMillis();
System.out.println("任务5耗时="+(end-begin));
return new AsyncResult<String>("任务5");
}
public Future<String> task6() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(1000L);
long end = System.currentTimeMillis();
System.out.println("任务6耗时="+(end-begin));
return new AsyncResult<String>("任务6");
}
}
注释:Future用来控制异步任务,通过isDone方法判断异步任务是否完成
3、在Controller中测试,两种测试方法。
3.1一种不等异步任务运行完,结束主任务,可快速将结果反馈用户
@Autowired
AsyncTask asyncTask;
@GetMapping(“asyncTask”)
/**
* 不等异步任务运行完,结束主任务
* @return
* @throws InterruptedException
*/
public Object asyncTask() throws InterruptedException{
Long start=System.currentTimeMillis();
asyncTask.task1(); //异步任务
asyncTask.task2(); //异步任务
asyncTask.task3(); //异步任务
Long end=System.currentTimeMillis();
Long count=end-start;
System.out.println("count:"+count); //计算主任务时间
return JsonData.buildSuccess(count);
}
测试结果
count:8 //主任务用时
task1总用时1001
task2总用时2001
task3总用时3001
3.2一种等异步任务运行完,结束主任务
@GetMapping("asyncTask2")
public Object asyncTask2() throws InterruptedException{
long begin = System.currentTimeMillis();
Future<String> task4 = asyncTask.task4();
Future<String> task5 = asyncTask.task5();
Future<String> task6 = asyncTask.task6();
for(;;){
if (task4.isDone() && task5.isDone() && task6.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
long total = end-begin;
System.out.println("执行总耗时="+total);
return JsonData.buildSuccess(total);
}
测试结果
任务6耗时=1001
任务4耗时=2001
任务5耗时=3001
执行总耗时=3034 //主任务用时
如果要测试同步,则把@Async注释掉
推荐大家一个java学习网站 https://how2j.cn/p/5976