当前位置:网站首页>@Async 没有异步执行
@Async 没有异步执行
2022-07-24 05:19:00 【我惠依旧】
失效原因
[email protected]启动类当中没有添加@EnableAsync注解。
2.异步方法使用注解@Async的返回值只能为void或者Future。
3.没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器管理。
问题代码:
一个类中调用了本类的方法,没有走代理对象。
@PostConstruct
public void test(){
Long a = System.currentTimeMillis();
try {
test1();
test2();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
}
@Async("")
public void test1() throws InterruptedException {
System.out.println(1);
Thread.sleep(10000);
System.out.println(2);
}
@Async("")
public void test2() throws InterruptedException {
System.out.println(3);
Thread.sleep(10000);
System.out.println(4);
}执行结果就是
1->2->3->4
解决:
增加接口类和实现类
public interface DataService {
public void test1();
public void test2();
}实现类:
@Service
public class DataServiceImpl implements DataService {
@Override
@Async("asyncServiceExecutor")
public void test1() {
System.out.println(1);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(2);
}
@Override
@Async("asyncServiceExecutor")
public void test2() {
System.out.println(3);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(4);
}
}调用:
@Autowired
private DataService dataService;
@PostConstruct
public void test(){
Long a = System.currentTimeMillis();
dataService.test1();
dataService.test2();
System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
}执行结果就是
1->3->2->4 或者1->3->4->2
边栏推荐
猜你喜欢
随机推荐
登录 页面 + 总结心得
Vscode configuring autoprefixer
MySQL之CRUD
Collection = = academic waste
Constructor_ Date constructor
整站下载器推荐
Draw a circle and a square on the screen. The square is in front and the circle is behind. You can move the square through the keyboard. In the following cases, the square can only move within the cir
量化合约夹子套利机器人系统逻辑开发原理分析
函数_概括
Tabs tab (EL tabs)_ Cause the page to jam
闲来写博~简单说说let和var和const
再次聊聊浏览器缓存
关于作为行业人从业人员的一点思考
作用域与作用域链
Create a new UMI project, error: rendered more hooks or rendered fewer hooks
Some thoughts on being a professional
index为什么不能作为v-for的key?
CESS 测试网上线!首个提供多元应用场景的去中心化存储网络
Polkadot | 一文解读颠覆传统社媒的Liberty计划如何在波卡落地
vulnhub-SolidState: 1靶机渗透测试









