gpt4 book ai didi

java - Spring的@Async忽略synchronized?

转载 作者:行者123 更新时间:2023-11-30 06:20:25 25 4
gpt4 key购买 nike

我在服务类中有这个方法:

@Service
public class Service {
@Async
public synchronized void asyncTest() {
try {
System.out.println("entered");
Thread.sleep(5000);
System.out.println("exited");
System.out.println(this);
}
catch (InterruptedException e ) {}
}
}

当我打电话时

@Test
public void asyncTest() throws InterruptedException {
service.asyncTest();
service.asyncTest();
Thread.sleep(10000);
}

它产生:

entered
entered
exited
exited
...Service@26d74d5f
...Service@26d74d5f

尽管我期望

entered
exited
...Service@26d74d5f
entered
exited
...Service@26d74d5f

由于synchronized关键字。为什么?

我的xml配置:

<task:annotation-driven mode="aspectj" executor="fisExecutor" scheduler="fisScheduler"/>
<task:executor id="fisExecutor" pool-size="10" />
<task:scheduler id="fisScheduler" pool-size="30" />
<task:executor keep-alive="60" id="cmsExecutor" pool-size="5-00" queue-capacity="0" rejection-policy="CALLER_RUNS"/>

Spring 版本:4.1.9.RELEASEJDK 1.7

测试类注释:

   @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/applicationContext-*.xml")

最佳答案

一种方法是更改​​方法签名,以确保您从可以控制的 API 中获取异步对象。例如,您可以修改代码以包含 CompletableFutures,模仿如下所示:

  @Service
public class Service {
@Async
public CompletableFuture<Void> asyncTest() {
try {
System.out.println("entered");
Thread.sleep(5000);
System.out.println("exited");
System.out.println(this);
}
catch (InterruptedException e ) {}

return new AsyncResult<Void>(null);
}
}

我使用此网站获取片段和调查资源:http://www.baeldung.com/spring-async

关于java - Spring的@Async忽略synchronized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48266649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com