【问题标题】:java multithreading , creating object for each threadjava多线程,为每个线程创建对象
【发布时间】:2014-12-10 04:57:09
【问题描述】:

我有两个类 CallISPSubscriberDump(这个类从数据库中读取进程 ID 总数,对于每个进程 ID,它调用 ISPSubscriberDump 类来创建一个文件)和 ISPSubscriberDump(用于创建 ISP 订阅者转储文件,该文件被发送到网络进行供应)。 我正在使用 Executor Service 创建多个线程并在其构造函数中将进程 id 传递给 ISPSubscriberDump,但在这种方法中,我必须创建与正在运行的线程一样多的对象。这个过程运行良好。 由于我必须为每个进程 Id 运行一个线程,有没有其他方法可以只创建单个对象并创建多个对象?

public class CallISPSubscriberDump
{

    public  void createFile()
    {

        List<Integer> totalId = new ArrayList<Integer>();
        List<String> dataFlag = new ArrayList<String>();


        //Reading process Id and dataFlag from database and populating in list
        try
        {
            if (totalId.size() == 0)
            {
                throw new Exception("No process id found for ISP Dump");
            }
            else
            {
                // MAX_THRAED is max limit of threads
                int maxthred = totalId.size() < Integer.parseInt(logGererator.getProperty("MAX_THRAED")) ? totalId.size() :
                                                Integer.parseInt(logGererator.getProperty("MAX_THRAED"));

                ExecutorService executor = Executors.newFixedThreadPool(maxthred);

                for (int cnt = 0; cnt < totalId.size(); cnt++)
                {
                    //For a particular thread assigning a particular process I create N object of ISPSubscriberDump for N thread and assign process Id in its constructor
                    executor.execute(new ISPSubscriberDump(totalId.get(cnt),dataFlag.get(cnt)));
                }

                executor.shutdown();

                while (!executor.isTerminated())
                {
                }
                System.out.println("Finished all threads");


            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
public class ISPSubscriberDump implements Runnable 
{

    private int processId;
    private String dataFlag;

    public ISPSubscriberDump(int processId,String dataFlag){
        this.processId=processId;
        this.dataFlag=dataFlag;
    }

    public void run()
    {
        // File Creation 
        createFile();
    }

    createFile()
    {
    int currentProcessId=processId;
    String currentDataFlag= dataFlag;
    // File Creation and provising happened here using currentProcessId and currentDataFlag
    }

    }

【问题讨论】:

  • 您可以使用队列并让您的线程从那里挑选对象任务。
  • 即使使用队列我也无法解决,请您详细解释一下

标签: java multithreading executorservice


【解决方案1】:

TL;DR

“有没有其他方法可以只创建单个对象并创建多个对象?”

也许您可以使用单例/工厂类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2019-05-01
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多