【问题标题】:Multiple threads HashTable in javajava中的多线程HashTable
【发布时间】:2012-10-16 02:27:41
【问题描述】:

MainThread 有一个 HashTable,它保存了从 customId 到 SubThread 对象的映射,并将任务放到映射中。 SubThread 从地图中删除任务。 如何避免这个问题?

线程 1:

public void start()
{
        subThreadMap = new Hashtable<Integer, SubThread>();
        while(true)
        {
            List<CloudPusherTaskInfo> taskInfos = TestDao.getTasks();

        for (CloudPusherTaskInfo task : taskInfos)
        {
            distribute(task);
        }
    }
}

private void distribute(CloudPusherTaskInfo task)
{
    SubThread subThread = null;

    if(subThreadMap.containsKey(task.getCustomerId()))
    {
        /*
         * if subThread exist, add a task to it
         */
        subThread = subThreadMap.get(task.getCustomerId());

/* -----at this point, the other subThread maybe end, and return null--------*/

        subThread.add(task);
    }
    else
    {
        /*
         * if subThread is not exist, create a new subthread, then add a task and run it 
         */
        SubThread newThread = createNewSubThread(task.getCustomerId());
        subThread = subThreadMap.put(task.getCustomerId(), newThread);
        newThread.add(task);
        new Thread(newThread).start();
    }
}

【问题讨论】:

  • 你的问题到底是什么???你想避免哪个问题?

标签: java multithreading hashtable


【解决方案1】:

如果我理解正确,子线程可能已经完成了它的任务并在调用subThreadMap.containsKey()subThreadMap.get() 之间结束。

不要重新发明轮子。您应该查看 java.util.concurrent 包中的类,它提供了完成线程池和任务执行所需的所有功能。

【讨论】:

    【解决方案2】:

    如果它的主要目的是获取 Thread 对象并启动它们,则不需要 HashTable Hashtable&lt;Integer, SubThread&gt;();。让 CloudPusherTaskInfo 实现 Runnable 接口,然后使用Executor.execute(new CloudPusherTaskInfo())。或者您可以将 CloudPusherTaskInfo 任务保存在一个列表中并一个接一个地执行它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 2011-08-07
      相关资源
      最近更新 更多