Created
June 9, 2016 23:21
-
-
Save ssuarez6/b0c81f102f119ff5e90f63e8b339a114 to your computer and use it in GitHub Desktop.
This file contains 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
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