Java使用线程

时间:2014-02-22 01:42:18

标签: 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; 

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

我想要的行为:当Thread1将对放入映射时,thread2检查它们的名称是否匹配一对,如果是,则打印它的值。

我得到的行为:

//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)

1 个答案:

答案 0 :(得分:0)

等待/通知的调用必须在同步块内和while循环中:

尝试:

synchronize(map) {
    while(!map.size() > 0){
         try {
             map.wait()
         catch(InterruptedException e) {}
    }
}

然后在使用map.notify()放入一些项目后通知线程。