Java使用线程
我有两种类型的线程 Thread1:填充多线程安全数据结构 Thread2的:在数据结构中搜索特定键 我想在地图中没有任何数据之前启动thread2,因此我的做法是:Java使用线程,java,multithreading,Java,Multithreading,我有两种类型的线程 Thread1:填充多线程安全数据结构 Thread2的:在数据结构中搜索特定键 我想在地图中没有任何数据之前启动thread2,因此我的做法是: //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; pub
//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));
}
}
}
对wait/notify的调用必须位于同步块内和while循环中: 尝试:
然后在将某些项目放入后通知线程:
map.notify()
很难说清楚你在做什么。请发布一个简短但完整的示例,我们可以用它来重现您正在描述的内容。如果您有两个线程输出到控制台,那么它们的输出当然会混合在一起。如果这不是您想要的,请不要这样做。我添加了一些psuedoish代码,以尝试显示我正在尝试完成的任务。问题不在于输出的打印顺序。问题是,有时输出在映射中找不到匹配项,即使它们存在。
//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)
synchronize(map) {
while(!map.size() > 0){
try {
map.wait()
catch(InterruptedException e) {}
}
}