1.主类配置@EnableAsync开启多线程配置
@SpringBootApplication
@EnableAsync //开启异步调用
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
2.方法块添加@Async注解
@Service
public class HelloServiceImpl implements HelloService {
@Override
@Async
@Transactional
public void sayHello() {
System.out.println("sayHello当前线程名称:"+Thread.currentThread().getName());
}
}
3.调用测试
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/hello")
public String hello(){
System.out.println("当前线程名称:"+Thread.currentThread().getName());
helloService.sayHello();
return "hello";
}
@Async
public void async(){
System.out.println("async当前线程名称:"+Thread.currentThread().getName());
}
}
打印结果:
当前线程名称:http-nio-8085-exec-1
async当前线程名称:http-nio-8085-exec-1
2019-12-19 12:15:07.683 INFO 4560 --- [nio-8085-exec-1] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
sayHello当前线程名称:SimpleAsyncTaskExecutor-1
结果表明,当调用其他类的被Async注解的方法时,会开启一个新的线程处理,而调自己类的Async注解的方法时,是不会开启一个新的线程