2012-10-16 44 views
0

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

實際上你的問題是什麼?你想避免哪個問題? –

回答

2

如果我理解正確的話,這是可能的子線程來完成它的任務和通話之間端到subThreadMap.containsKey()subThreadMap.get()

不要重新發明輪子。您應該查看包java.util.concurrent中的類,它提供了完成線程池和任務執行所需的所有功能。

1

如果主要原因是獲取Thread對象並啓動它們,則不需要HashTable Hashtable<Integer, SubThread>();。使CloudPusherTaskInfo實現Runnable接口,然後使用Executor.execute(new CloudPusherTaskInfo())。或者,您可以將CloudPusherTaskInfo任務保存在列表中並逐個執行它們。