Programming Tutorials

Comment on Tutorial - wait(), notify() and notifyAll() in Java - A tutorial By Jagan



Comment Added by : Hdm-Student

Comment Added at : 2010-06-16 08:10:51

Comment on Tutorial : wait(), notify() and notifyAll() in Java - A tutorial By Jagan
Hello,

your solution is kinda overkill.
When used correctly, notify and wait don't need workarounds such as valueSet.

Here's the improved version:
----------------------
package producer;

// A correct implementation of a producer and consumer.
class Q {
int n;

synchronized int get() {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
return n;
}

synchronized void put(int n) {
try {
notify();
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
System.out.println("Put: " + n);
}
}

public class Producer implements Runnable {
Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}

class Consumer implements Runnable {
Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {
while (true) {
q.get();
}
}
}

class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

-------------------------


View Tutorial