Last active
December 1, 2015 09:16
-
-
Save rishi93/63c3e84fb44d61e474ab to your computer and use it in GitHub Desktop.
Producer Consumer Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.lang.*; | |
class Factory | |
{ | |
private int contents; | |
private boolean available = false; | |
public synchronized int get() | |
{ | |
while(!available) | |
{ | |
try | |
{ | |
wait(); | |
} | |
catch(InterruptedException e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
available = false; | |
notify(); | |
return contents; | |
} | |
public synchronized void put(int contents) | |
{ | |
while(available) | |
{ | |
try | |
{ | |
wait(); | |
} | |
catch(InterruptedException e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
available = true; | |
this.contents = contents; | |
notify(); | |
} | |
} | |
class Producer extends Thread | |
{ | |
private Factory factory; | |
Producer(Factory factory) | |
{ | |
this.factory = factory; | |
} | |
public void run() | |
{ | |
int randval; | |
for(int i = 0; i < 10; i ++) | |
{ | |
randval = (int)(1+Math.random()*100); | |
factory.put(randval); | |
System.out.println("Producer put " + randval); | |
try | |
{ | |
sleep( (int)(1+Math.random()*5)*100 ); //Just wait for random time after producing | |
} | |
catch(InterruptedException e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
class Consumer extends Thread | |
{ | |
private Factory factory; | |
Consumer(Factory factory) | |
{ | |
this.factory = factory; | |
} | |
public void run() | |
{ | |
int val; | |
for(int i = 0; i < 10; i++) | |
{ | |
val = factory.get(); | |
System.out.println("Consumer got " + val); | |
} | |
} | |
} | |
public class Main | |
{ | |
public static void main(String[] args) | |
{ | |
Factory f1 = new Factory(); | |
Producer p1 = new Producer(f1); | |
Consumer c1 = new Consumer(f1); | |
p1.start(); | |
c1.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment