我需要在 Spring 应用程序中启动可变数量的线程,每个线程又启动不同数量的线程(即第 i 个线程,其中第 I 个线程需要启动 Ki 线程)。
假设每个“I 线程”都包含一个 Autowiring 的内部类,我将如何生成这些实例?
所以我有一个 A bean
,它需要以某种方式生成一个 I
的 bean 实例,该实例需要由 spring 管理以满足其依赖关系。
我编写了一个简短的示例代码,我认为这是我的解决方案的基础,并且我已经标记了我不知道如何编写的代码???:
@Component
public class MasterOrchestrator {
public void do(List<DataObjWrapper> list){
ExecutorService es = Executors.newFixedThreadPool(list.size());
for (DataObjWrapper dataObjWrapper : list){
es.submit(???);
}
}
}
@Component
public class ThreadWorkerI implements Runnable{
private int numThreadsForMessageType;
private int numRunsForMessageType;
private DataObj dataObj;
public ThreadWorkerI(int numThreadsForMessageType, int numRunsForMessageType, DataObj dataObj){
this.numThreadsForMessageType = numThreadsForMessageType;
this.numRunsForMessageType = numRunsForMessageType;
this.dataObj = dataObj;
}
@Autowired
private JmsTemplate jmsTemplate;
public void run(){
ExecutorService es = Executors.newFixedThreadPool(numThreadsForMessageType);
for (int i=0;i<numRunsForMessageType;i++){
es.submit(new ActualWorker(i));
}
}
private class ActualWorker implements Runnable{
private int numRun;
private ActualWorker(int numRun){
this.numRun = numRun;
}
public void run(){
//send message using the jmsTemplate the dataObj and numRun
}
}
}
DatObjWrapper
包含 numThreadsForMessageType
、numRunsForMessageType
和 dataObj
等成员。
最佳答案
您可以使用@Configurable注释,让 Spring 将依赖项注入(inject)到您的工作线程中 - 即使是那些没有由 Spring 容器显式管理的依赖项。
关于java - Spring和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7365971/