1
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 会唤醒吗?

4

1 回答 1

3

您正在等待并通知 2 个不同的对象 - 因此它们不会互相交谈。您需要使用一个公共对象并在该公共对象上调用waitnotifyAll方法。

例如:

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其设为私有和最终以确保引用不会在外部更改。
  • 同步块的监视器现在队列本身而不是this.
于 2013-02-05T14:11:57.500 回答