Skip to content

Instantly share code, notes, and snippets.

@gourab5139014
Last active August 29, 2015 14:10
Show Gist options
  • Save gourab5139014/520b31476883e84aa51c to your computer and use it in GitHub Desktop.
Save gourab5139014/520b31476883e84aa51c to your computer and use it in GitHub Desktop.
Implementation of Producer Consumer Problem in Java using threads
import java.util.logging.Level;
import java.util.logging.Logger;
//Producer Consumer using Threads
public class ProducerConsumerTest
{
public static void main(String args[])
{
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Producer p2 = new Producer(c, 2);
Consumer c1 = new Consumer(c, 1);
Consumer c2 = new Consumer(c, 2);
p1.start();
p2.start();
c1.start();
c2.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get(int who) {
while (available == false) { //sleep on not available
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
System.out.println("Consumer " + who + " got: " + contents);
notifyAll();
return contents;
}
public synchronized void put(int who, int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
System.out.println("Producer " + who + " put: " + contents);
notifyAll();
}
}
class Producer extends Thread
{
private CubbyHole cubbyhole;
private final int number; //Thread Number
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(number, i);
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private final int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
@Override
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get(number);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment