Wait()和NotifyAll()

时间:2013-02-05 14:07:21

标签: java multithreading

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

1 个答案:

答案 0 :(得分: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