Reputation: 1058
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?
Upvotes: 1
Views: 141
Reputation: 328568
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:
q
private and final to make sure the reference is not changed externally.this
.Upvotes: 3