【发布时间】:2023-03-28 09:58:01
【问题描述】:
我有 3 个服务类(现在,假设 A、B、C)。它们中的每一个实际上都是一个线程。在我的要求中,他们每个人都应该有一个无限循环。但是每当我运行一个服务类时,其他服务类的无限循环 bean 都不会创建。
如果没有无限循环,则创建每个类的 bean。为什么会这样?
假设它是服务 A。
@Service
@Log4j2
public class A implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("A Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
假设它是服务 B。
@Service
@Log4j2
public class B implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("B Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
假设它是服务 C。
@Service
@Log4j2
public class C implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("C Thread Started!");
while (isRunning) {
// just a sleep for 2 sec
}
}
}
这是我的主要课程:
@SpringBootApplication
@Log4j2
public class Main {
@Autowired
public ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
@PostConstruct
public void createConnection() {
log.debug("Connecting to Server...");
// doing some staff
}
}
现在如果我这样运行,总是得到这个日志:
2020-07-14 21:21:52:129 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'a'
2020-07-14 21:21:52:130 [main] DEBUG service.ProcessorService:27 - A Thread Started!
如果我将任何日志放入 A 类的 while 循环中,那么只会显示那些日志。
如果我对 A 类的循环部分进行评论并保持该类如下:
@Service
@Log4j2
public class A implements Runnable {
private boolean isRunning = true;
@Override
@PostConstruct
public void run() {
log.debug("A Thread Started!");
/* while (isRunning) {
// just a sleep for 2 sec
}*/
}
}
然后在日志中得到这个:
2020-07-14 21:30:31:198 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'a'
2020-07-14 21:30:31:199 [main] DEBUG service.ProcessorService:27 - A Thread Started!
2020-07-14 21:30:31:199 [main] DEBUG support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'b'
2020-07-14 21:30:31:199 [main] DEBUG service.ReceivingProcessingService:46 - B Thread Started!
如果我也评论 B 类的循环部分,那么只会让每个服务类运行。无法理解原因。任何帮助将不胜感激。
【问题讨论】:
标签: java spring-boot