@Async注释的service的方法,在使用的时候,应该直接调用到,而不是通过一个方法再调用这个异步的方法
我新建一个TestService的类,包含了test1、test2、test3的方法,其中test2、test3是加了@Async标签的。:
public void test1(){
test2();
test3();
}
@Async
public void test2(){
long start = System.currentTimeMillis();
try {
Thread.currentThread().sleep(20*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start + "毫秒过去了");
}
@Async
public void test3(){
long start = System.currentTimeMillis();
try {
Thread.currentThread().sleep(30*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start + "毫秒过去了");
}
之后我在一个controller里边这么调用,
@PostMapping(value = "/f01")
@ResponseBody
public void test11(){
testService.test2();
testService.test3();
this.renderSuccess("成功");
}
@PostMapping(value = "/f02")
@ResponseBody
public void test11(){
testService.test1();
this.renderSuccess("成功");
}
结果发现:
f01方法之后,立马返回了成功的信息,异步方法的确在执行了。
f02方法之后,等了50多秒才返回了成功的信息,异步方法并没有异步的执行,而是同步的执行了。
@Async
public void test4(){
test4();
}
public void test5(){
long start = System.currentTimeMillis();
try {
Thread.currentThread().sleep(20*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start + "毫秒过去了");
}
test4()是加了@Async标签的,
之后我在一个controller里边这么调用,
@PostMapping(value = "/f03")
@ResponseBody
public void test11(){
testService.test4();
this.renderSuccess("成功");
}
结果发现:
f03方法之后,立马返回了成功的信息,异步方法的确在执行了。