@Async 没有异步执行

失效原因

1.@SpringBootApplication启动类当中没有添加@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

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值