简体   繁体   中英

Wait() and NotifyAll()

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); }
            }
        }    
    }

And I have another class that adds items to the same object SyncQueue and does 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); }
        }
    }
}
} 

Will the SimpleConsumer wake up if I do notifyAll() from a different class method?

You are waiting and notifying on 2 different objects - so they won't talk to each other. You need to use a common object and call the wait and notifyAll methods on that common object.

For example:

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); }
        }
    }    
}

Note:

  • I have made q private and final to make sure the reference is not changed externally.
  • the monitor for the synchronized block in now the queue itself instead of this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM