java - Spring和多线程

标签 java multithreading spring ioc-container autowired

我需要在 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 包含 numThreadsForMessageTypenumRunsForMessageTypedataObj 等成员。

最佳答案

您可以使用@Configurable注释,让 Spring 将依赖项注入(inject)到您的工作线程中 - 即使是那些没有由 Spring 容器显式管理的依赖项。

关于java - Spring和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7365971/

相关文章:

java - 如何在所有 Activity 中显示 Timer 的剩余时间?

java - 如何测试定时器?

java - Spring-Boot-Jersey 设置 CORS

java - Spring Boot 测试 - 没有合格的 Bean 异常

java - Apache Spark Reduce 与 java.lang.Math.max 意外行为

java - 如何测试在 JUnit 中的测试方法下创建的线程的完成情况

c - C 线程程序中的链接器错误..ld 返回 1 退出状态

vb.net - 如何使用带有BlockingCollection的WebClient正确实现线程下载?

android - IntentService 或 JobScheduler 在 onPause 期间执行 I/O 密集型数据保存操作

spring - @PreDestroy 未在 tomcat 关闭时调用 session 范围的 Spring bean