Spring應用程式在服務中旋轉著一個無休止的回圈
@Service
public class MyService {
public boolean isStart = false;
@Async("threadPoolTaskExecutor")
public void sending() {
while (isStartService) {
...
}
}
}
@Service
public class OneService {
@Autowired
private final MyService myService;
public void start(boolean isStautus) {
myService.isStart = true;
myService.sending();
}
}
在另一個服務中,我設定變數的值為 Start Service = true。雖然此方法沒有 Async 注釋,但一切正常。但是一旦它被添加,并且它開始在一個單獨的執行緒中運行,這個方法中的 isStartService 變數現在總是 = false。回圈永遠不會執行。如何在此流中正確傳遞此變數的值。即起初它應該是真的,一段時間后它的值被傳遞為假,因此該方法停止作業。
我試圖將 isStart 變數設定為 volatile。它沒有幫助
uj5u.com熱心網友回復:
問題是@Async觸發了 a 的創建proxy,因此當您直接改變變數時,代理不會攔截該呼叫。
setter為該屬性創建一個isStart,它將起作用。
此應用程式與 setter 一起按預期作業。您應該使該欄位volatile始終獲取該欄位的更新值。
@SpringBootApplication
@EnableAsync
public class SO72313483 {
public static void main(String[] args) {
SpringApplication.run(SO72313483.class, args);
}
private final static Logger logger = LoggerFactory.getLogger(SO72313483.class);
@Service
public static class MyService {
private volatile boolean isStartService = false;
@Async("taskExecutor")
public void sending() throws Exception {
while (isStartService) {
logger.info("Here");
Thread.sleep(5000);
}
}
public void setStartService(boolean startService) {
isStartService = startService;
}
}
@Service
public static class OneService {
@Autowired
private MyService myService;
public void start(boolean isStatus) throws Exception{
myService.setStartService(true);
myService.sending();
}
}
@Autowired
OneService oneService;
@Bean
ApplicationRunner runnerSO72313483() {
return args -> oneService.start(true);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479456.html
