class Q {
int n;
boolean valueSet = false;
synchronized int get() {
// Wait until the value is produced
if (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception caught");
}
}
System.out.println("Consumed " + n);
valueSet = false;
notify(); // Notify the producer to produce the next item
return n;
}
synchronized void put(int n) {
// Wait if the value is already produced (buffer is full)
if (valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Produced " + n);
notify(); // Notify the consumer to consume the item
}
}
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 && i < 7) {
q.put(i++);
try {
Thread.sleep(500); // Slow down the producer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
q.get();
try {
Thread.sleep(500); // Slow down the consumer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: