class MyObject{
private Queue<String> queue = new ConcurrentLinkedQueue<String>();
public synchronized void set(String s){
while(queue.size() >= 10){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(s);
notify();
}
}
class Producer implements Runnable{
private MyObject myObj;
public Producer(MyObject myObj) {
this.myObj= myObj;
}
@Override
public void run() {
// 每條線程執(zhí)行30次set
for (int i = 0; i < 30; i++) {
this.myObj.set("obj:" + i);
}
}
}
public static void main(String[] args){
Producer producer = new Producer(new MyObject());
// 生成30條線程
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(producer);
thread.start();
}
// 運行結果是只set了30次
}
我的疑惑是notify()發(fā)布通知,為什么不會讓其他線程的wait()方法繼續(xù)執(zhí)行下去呢?
添加回答
舉報
0/150
提交
取消