class SimpleConsumer extends Threads {
public SyncQueue q;
SimpleConsumer(SyncQueue q) { this.q = q; }
public void run () { doit(); }
public synchronized void doit() {
while(true){
try{
while(q.isEmpty()) { wait(); }
System.out.println((String)q.Dequeue());
}
catch (Exception e) { System.out.println("Got exception:" +e); }
}
}
}我还有另一个类,它将项目添加到同一个对象SyncQueue中,并执行notifyAll();
class SimpleProducer extends Threads {
public SyncQueue q;
SimpleProducer(SyncQueue q) { this.q = q; }
public void run() { doit(); }
public synchronized void doit() {
while(true){
try{
sleep(1000);
q.Enqueue("Item");
notifyAll();
} catch(Exception e) { System.out.println("Got exception:" +e); }
}
}
}
} 如果我从不同的类方法执行notifyAll(),SimpleConsumer会被唤醒吗?
发布于 2013-02-05 22:11:58
您正在等待并通知两个不同的对象--这样它们就不会相互通信。您需要使用一个公共对象,并对该公共对象调用wait和notifyAll方法。
例如:
class SimpleConsumer extends Threads {
private final SyncQueue q;
SimpleConsumer(SyncQueue q) {
this.q = q;
}
public void doit() {
while(true){
try{
synchronized(q) {
while(q.isEmpty()) { q.wait(); }
System.out.println((String)q.Dequeue());
}
}
catch (Exception e) { System.out.println("Got exception:" +e); }
}
}
}注意:
现在是队列本身而不是this.,我已经将
q和q,以确保引用不会更改为同步块的监视器https://stackoverflow.com/questions/14709396
复制相似问题