Skip to content

Instantly share code, notes, and snippets.

@ssuarez6
Created June 9, 2016 23:21
Show Gist options
  • Save ssuarez6/b0c81f102f119ff5e90f63e8b339a114 to your computer and use it in GitHub Desktop.
Save ssuarez6/b0c81f102f119ff5e90f63e8b339a114 to your computer and use it in GitHub Desktop.
public class ProducerConsumer{
static final int N = 100; //buffer size
static producer p = new producer();
static consumer c = new consumer();
static monitor m = new monitor();
public static void main(String args[]){
p.start();
c.start();
}
static class producer extends Thread{
public void run(){
int item;
while(true){
item = produceItem();
m.insert(item);
}
}
private int produceItem(){
return (int)(Math.random()*100);
}
}
static class consumer extends Thread{
public void run(){
int item;
while(true){
item = m.remove();
consumeItem(item);
}
}
private void consumeItem(int item){
System.out.println("Item consumido: " + item);
}
}
static class monitor{
private int buffer[] = new int[N];
private int count = 0, lo = 0, hi = 0;
public synchronized void insert(int val){
if(count == N) goToSleep();
buffer[hi] = val;
hi = (hi + 1) % N;
count++;
if (count == 1) notify();
}
public synchronized int remove(){
int val;
if (count == 0) goToSleep();
val = buffer[lo];
lo = (lo+1) % N;
count--;
if(count == N - 1) notify();
return val;
}
private void goToSleep(){
try{
wait();
}catch(InterruptedException iex){}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment