You need to wait()
and notify()
on some shared object. What you are doing now by using synchronized is waiting on the respective objects themselves, i.e. the Producer is waiting on the Producer and the Consumer on the Consumer object. You need to wait on something in Q.
From the Javadoc:
notify(): Wakes up a single thread that is waiting on this object's monitor.
wait(): The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
This object's monitor in your case is this
, which is your Producer
in the put()
case and the Consumer
in the get()
case. But in order for the notify to notify the other Thread, they need to have the same monitor, i.e. they need to wait()
on the same object. This object can be e.g. a Object variable in your Q
.
To get you started, this is what I mean:
class Q
{
static boolean valueset=false;
static int i;
static Object myLock = new Object();
}
public void put() {
synchronized (Q.myLock) {
while (Q.valueset) {
try {
Q.myLock.wait();
} catch (Exception e) {
System.out.println(e);
}
}
Q.i++; //you forgot this as well
System.out.println("Put:" + Q.i);
Q.valueset = true;
Q.myLock.notify();
}
}
You can fill in the Consumer class yourself...
Put:1
Get:1
Put:2
Get:2
Put:3
Get:3
Put:4
Get:4