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
waitandnotifyAllmethods on that common object.For example:
Note:
qprivate and final to make sure the reference is not changed externally.this.