-2
工作,我有兩種類型的線程與Java線程
線程1的:填充一個多線程安全的數據結構
線程2的:搜索的數據結構
我要開始一個特定的密鑰線程2的前出現在地圖的任何數據,所以我這樣做的方式是:
//Main
spawn 3 new thread 2's(name, map)
spawn 3 new thread 1's(name, value, map)
let threads handle rest
//Thread1
private string name;
private string value;
public void run(){
try{
synchronized(map){
map.put(key, value);
map.notifyAll();
}
}
}
//Thread2
private string name;
public void run(){
try{
synchronized(map){
while (map.size() <1){
map.wait();
}
}
if (map.containsKey(name){
System.out.println(name, map.get(name));
}
}
}
我想要的行爲:由於線程1的put對進入地圖,線程2的c係數嘿,如果他們的名字匹配一對,如果是這樣打印它的價值。
行爲我越來越:
//Result
Putting bluecheese -- white//This line is printed in thread 1 right before the map.put call
Putting chipotle -- food
Putting dogbone -- dog
food
**** should have been food, dog, white (no order to this, just make sure we account for them all)
//Result #2
Putting bluecheese -- white//This line is printed in thread 1 right before the map.put call
Putting chipotle -- food
Putting dogbone -- dog
white, dog //This line is printed in thread 2.
**** should have been white, dog, food (no order, again just make sure we account for them all)
很難說清楚你在做什麼。請發佈一個簡短但完整的示例,我們可以使用它來重現您正在描述的內容。 –
如果你有兩個線程輸出到控制檯,它們的輸出當然是混合的。如果這不是你想要的,不要這樣做。 – keshlam
我已經添加了一些僞代碼來試圖展示我想要完成的事情。 –