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 会唤醒吗?
最佳答案
您正在等待和通知 2 个不同的对象 - 因此它们不会相互交谈。您需要使用一个公共(public)对象并对该公共(public)对象调用 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); }
}
}
}
注意:
- 我已将
q
设为私有(private)和最终状态,以确保引用不会被外部更改。 - 同步块(synchronized block)的监视器现在在队列本身而不是
this
中。
关于java - Wait() 和 NotifyAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14709396/