Java includes an interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context.
wait( )
tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
notify( )
wakes up a thread that called wait( ) on the same object.
notifyAll( )
wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions:
class SharedBox {
int n;
boolean valueSet = false;
synchronized int get() {
while (!valueSet)
try {
wait();
} catch (Exception e) {
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while (valueSet)
try {
wait();
} catch (Exception e) {
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
SharedBox box;
Producer(SharedBox q) {
this.box = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (true) {
box.put(i++);
}
}
}
class Consumer implements Runnable {
SharedBox box;
Consumer(SharedBox q) {
this.box = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
box.get();
}
}
}
public class Main {
public static void main(String args[]) throws Exception {
SharedBox q = new SharedBox();
new Producer(q);
new Consumer(q);
Thread.sleep(2000);
System.exit(0);
}
}