0

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();
    }
}
4

2 回答 2

2

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

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

于 2012-10-16T03:15:39.710 回答
1

The HashTable Hashtable<Integer, SubThread>(); is not needed if its primary reason is to get Thread objects and start them. Make the CloudPusherTaskInfo implement the Runnable interface and then use the Executor.execute(new CloudPusherTaskInfo()). Or you could hold the CloudPusherTaskInfo tasks in a List and execute them one after another.

于 2012-10-16T05:26:21.050 回答