当前位置:网站首页>@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
边栏推荐
猜你喜欢

Function analysis of GeoServer rest API

Station B video comment crawling - take the blade of ghost destruction as an example (and store it in CSV)

LaTeX学习笔记(一)——安装配置

special effects - 鼠标点击,出现随机颜色的爱心

node连接mysql,使用navicat可视化

jsp标签02

PHP 多行文字内容的重复检测功能并统计重复次数

How to forcibly uninstall Google browser? Don't worry about Google opening as a whiteboard. It's effective for personal testing.

渗透测试知识---行业术语

再次聊聊浏览器缓存
随机推荐
稀缺性之于Web3:如何成为去中心化世界的胜利者
【奖励发放】OneOS专区首届征文活动评奖结果公布
mapboxgl + geoserver 配置本地地图教程
微信小程序报错request:fail -2:net::ERR_FAILED
Vulnhub-Funbox: Rookie(Funbox2)靶机渗透
Polkadot | 一文解读颠覆传统社媒的Liberty计划如何在波卡落地
JS - 鼠标键盘配置 及 浏览器禁止操作
【百度地图API】您所使用的地图JS API版本过低,已不再维护,为保证地图基本功能 正常使用,请尽快升级到最新版地图JS API
special effects - 樱花飘落背景特效
6. Draw a Bezier curve and a Bezier surface on the screen
浏览器的本地存储
16进制转rgb
动画 效果
通用分页2.0
Hurry in!! Easily master the three structures of "sequence", "branch" and "cycle" of C language
Three -- orbitcontrols track controller
New grammar 01_ ES6 new syntax
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
牛客网刷题
canvas - 填充