Java中@Async注解无法实现异步执行的问题求助
Java中@Async注解无法实现异步执行的问题求助
兄弟,我一眼就瞅出你代码里的问题了!你的@Async没生效根本就不是配置的锅,核心问题出在静态方法和调用方式这两个点上,这俩都是Spring异步注解的常见坑!
问题1:@Async不能用在静态方法上
Spring的@Async是基于动态代理机制实现的,静态方法属于类本身,没办法被Spring的代理对象包裹,所以异步逻辑根本就织不进去。你把A、B方法都定义成static的,等于直接绕过了Spring的异步处理。
问题2:直接调用静态方法绕开了Spring代理
就算你把方法改成非静态,你在anotherServiceImpl里直接用AsyncServiceImpl.A()这种类名调用的方式,也等于直接调用了原始方法,没有走Spring生成的代理对象,自然也不会触发异步。
修正后的代码示例
1. 改造AsyncServiceImpl,去掉static,改为实例方法
@Service public class AsyncServiceImpl { @Async("processExecutor") public void A() { for(int i=0; i<100; i++){ System.out.println("A"); } } @Async("processExecutor") public void B() { for(int i=0; i<100; i++){ System.out.println("B"); } } }
2. 改造anotherServiceImpl,通过Spring注入的实例调用异步方法
@Service public class anotherServiceImpl implements anotherService{ // 注入AsyncServiceImpl的Spring管理实例 private final AsyncServiceImpl asyncService; // 推荐用构造方法注入(避免空指针,符合依赖注入规范) public anotherServiceImpl(AsyncServiceImpl asyncService) { this.asyncService = asyncService; } @Override public void C() { // 通过实例调用,才会触发Spring的异步代理 asyncService.A(); asyncService.B(); } }
额外确认点
你已经做对的地方我再帮你核对下:
- @EnableAsync加在启动类上:没问题,这是开启异步功能的前提
- 异步方法和调用方法不在同一个类:没问题,同一个类里调用也会绕开代理(不过你这里不存在这个问题)
- 线程池配置:核心线程数100足够同时跑A、B两个方法,配置没问题
改完之后,A和B就会在不同的线程里并行执行,输出就会变成你预期的A、B混合的样子,后续用来做数据库的saveAll这类操作也能正常异步执行啦!
备注:内容来源于stack exchange,提问作者Tommy Leong
相关产品推荐
相关产品推荐

