Skip to content

Instantly share code, notes, and snippets.

@GorvGoyl
Created July 12, 2015 20:49
Show Gist options
  • Save GorvGoyl/4edab1a8ba0da97c1df4 to your computer and use it in GitHub Desktop.
Save GorvGoyl/4edab1a8ba0da97c1df4 to your computer and use it in GitHub Desktop.
Producer Consumer problem - Solution using Wait() notify() in Java
import java.util.*;
public class InterThreadCommunicationExample {
public static void main(String args[]) {
final LinkedList<Integer> sharedQ = new LinkedList<Integer>();
Thread producer = new Producer(sharedQ);
Thread consumer = new Consumer(sharedQ);
producer.start();
consumer.start();
}
}
class Producer extends Thread {
private final LinkedList<Integer> sharedQ;
public Producer(LinkedList<Integer> sharedQ) {
this.sharedQ = sharedQ;
}
public void run() {
for (int i = 1; i < 11; i++) {
synchronized (sharedQ) {
//waiting condition - wait until Queue is not empty
while (sharedQ.size() >= 3) { //size of queue
try {
System.out.println("Queue is full, can't add");
sharedQ.wait(); //to prevent from infinite loop
} catch (Exception ex) {
}
}
try{
Thread.sleep(i*5); //invoke consumer thread
}catch(Exception e){}
System.out.println("producing : " + i);
sharedQ.add(i);
sharedQ.notify();
}
}
}
}
class Consumer extends Thread {
private final LinkedList<Integer> sharedQ;
public Consumer(LinkedList<Integer> sharedQ) {
this.sharedQ = sharedQ;
}
public void run() {
while(true) {
synchronized (sharedQ) {
//waiting condition - wait until Queue is not empty
while (sharedQ.size() == 0) {
try {
System.out.println("Queue is empty, can't remove");
sharedQ.wait();
} catch (Exception ex) {
}
}
try{
Thread.sleep(300); //invoke producer thread
}catch(Exception e){}
int number = sharedQ.poll();
System.out.println("consuming : " + number );
sharedQ.notify();
//termination condition
if(number == 10){break; }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment