弹簧和多线程 [英] Spring and Multithreading

查看:227
本文介绍了弹簧和多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要启动一个可变数量的线程,这些线程又会在spring应用程序中启动不同数量的线程(即I线程需要启动Ki线程的线程)。

假设每个线程I threads包含一个自动装配的内部类,我将如何生成这些实例?
所以我有一个一个bean ,它需要以某种方式生成需要的bean实例spring设法满足其依赖性。

I need to start a variable number of threads which in turn each start a varying number of threads (i.e. i threads where the Ith thread needs to start Ki threads) in a spring application.
assuming each of the "I threads" contains an inner class which is autowired how will I generate those instances? So I have an A bean which needs to somehow generate I instances of a bean which needs to be spring managed to satisfy its dependencies.

我写了一个简短的示例代码,我认为是我的解决方案的基础,我已经标记了代码,我不知道如何编写? ??:

I've written a short sample code of what I think is the base for my solution and I've marked the code I'm not sure how to write by ???:

@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

DatObjWrapper contains amongst other members the numThreadsForMessageType, numRunsForMessageType and dataObj.

推荐答案

您可以使用 @configurable 注释让Spring为您的工作者注入依赖关系 - 即使是那些未被Spring明确管理的工具容器。

You can use @Configurable annotation to let Spring inject dependencies into your workers - even the one's that are not managed explicitly by the Spring container.

这篇关于弹簧和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆