Producer - Consumer Problem Java
Producer - Consumer Problem implementation:
IntegerBuffer.java
Producer.java
Consumer.java
MainClass.java
IntegerBuffer.java
public class IntegerBuffer {
private int index;
private int[] buffer;
private final int SIZE = 2;
public IntegerBuffer() {
this.buffer = new int[SIZE];
}
public synchronized void add(int number) {
while (index == buffer.length - 1) {
try {
wait();
System.out.println("IntegerBuffer.add() waiting");
} catch (InterruptedException e) {
}
}
buffer[index++] = number;
notifyAll();
}
public synchronized int remove() {
while (index == 0) {
try {
wait();
System.out.println("IntegerBuffer.remove() waiting");
} catch (InterruptedException e) {
}
}
int returnVal = buffer[--index];
notifyAll();
return returnVal;
}
}
Producer.java
import java.util.Random;
public class Producer extends Thread {
private IntegerBuffer buffer;
public Producer(IntegerBuffer buffer) {
this.buffer = buffer;
}
public void run() {
Random rand = new Random();
while(true) {
int number = rand.nextInt();
buffer.add(number);
System.out.println("Produced : " + number);
}
}
}
Consumer.java
public class Consumer extends Thread {
private IntegerBuffer buffer;
public Consumer(IntegerBuffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
while(true) {
int number = buffer.remove();
System.out.println("Consumed : " + number);
}
}
}
MainClass.java
public class MainClass {
public static void main(String[] args) {
IntegerBuffer buffer = new IntegerBuffer();
Producer p = new Producer(buffer);
Consumer c = new Consumer(buffer);
p.start();
c.start();
}
}
Comments
Post a Comment