MainThread有一個HashTable,它保存從customId到SubThread對象的映射,並將任務放到映射中。 SubThread從地圖中刪除任務。 如何避免這個問題?java中的多線程HashTable
線程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();
}
}
實際上你的問題是什麼?你想避免哪個問題? –