一、在main函数的入口类上加@EnableAsync注解
二、在Service层定义需要异步执行的方法: (如果异步方法写在Controller里,不能异步执行)
@Service
public class HelloService {
@Async
public void forMethod(){ //Controller层只能直接调此方法,才能异步执行,或者另起一个方法,调用此方法,也可以异步执行
for (int i=0; i< 900000; i++){
System.out.println("--" + i + "--");
}
}
//调用这个方法时,forMethod方法也异步执行
public void syncMethod(){
System.out.println("task 1");
forMethod();
System.out.println("task 2");
}
}
三、在Controller层调用异步方法:
@RequestMapping(value = "/sync/test", method = RequestMethod.GET)
public String syncTest(){
System.out.println("sync test started...");
helloService.forMethod();
System.out.println("sync test finished...");
return "over";
}