所以我试图通过将我的java代码迁移到Spring Boot来学习Spring Boot。
我有一部分Java代码是这样的:
int threadLimit = 5, interval = 2;
ScheduledExecutorService ses = Executors.newScheduledThreadPool(threadLimit);
for (int i = 0; i < executionThreadLimit; i++) {
WorkerThread worker = new WorkerThread("WorkerThread");
ses.scheduleAtFixedRate(worker, 0, interval, TimeUnit.SECONDS);
}
这里WorkerThread
实现了Runnable
;
上述代码对应的 Spring boot 替代方案:
自定义池类:
@Configuration
public class Test {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
}
WorkerThread 类:
@Component
@Scope("prototype")
public class WorkerThread implements Runnable {
private Logger logger = LogManager.getLogger(this.getClass().getName());
private String threadName = null;
@Autowired
private AppParameter app;
@Override
public void run() {
logger.info("Thread :: " + this + " is running -- > " + app.getA() + " && " + app.getB());
}
}
测试类:
@Component
public class TestCommandLineRunner implements CommandLineRunner {
private final Logger logger = LogManager.getLogger(this.getClass().getName());
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Override
public void run(String... args) throws Exception {
int threadLimit = 5, interval = 2000; // these 2 are dynamic values but provided statically for testing purposes
for(int i = 0; i< threadLimit; i++) {
WorkerThread wt = new WorkerThread();
taskScheduler.scheduleAtFixedRate(wt, interval);
}
}
}
现在这就是我的问题出现的地方。如果我需要启动 5 个 WorkerThread
实例,我必须执行 WorkerThread wt = new WorkerThread();
但如果这样做,那么 WorkerThread
不再是 Spring 管理的 bean。
所以我的问题是如何创建一个线程池,其中线程类是 Spring 托管 bean?
我才开始使用 Spring Boot,因此有人介意帮助我吗?谢谢。
我已经引用了以下文档, https://www.baeldung.com/spring-task-scheduler https://mkyong.com/spring/spring-and-java-thread-example/ 但无法提出可行的解决方案。
最佳答案
您可以使用ObjectFactory
实例化它们
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private ObjectFactory<WorkerThread> threadFactory;
@Override
public void run(String... args) throws Exception {
int threadLimit = 5, interval = 2000; // these 2 are dynamic values but provided statically for testing purposes
for(int i = 0; i< threadLimit; i++) {
WorkerThread wt = threadFactory.getObject();
taskScheduler.scheduleAtFixedRate(wt, interval);
}
}
关于java - 使用 Spring 托管线程创建 Spring 线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60947127/