Complete with necessary functions this example code to implement a solution to the producer consumer problem discussed in class using Posix threads and semaphores. Assume that there is only 10 producer and 10 consumer. The output of your code should be similar to the following and it must run in infinite loop
import java.util.LinkedList;
public class Main {
public static void main(String[] args)
throws InterruptedException
{
final ProducerConsumer P = new ProducerConsumer();
Thread time = new Thread(new Runnable() {
public void run()
{
try {
P.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread tim = new Thread(new Runnable() {
public void run()
{
try {
P.consume();
}
catch (InterruptedException B) {
B.printStackTrace();
}
}
});
time.start();
tim.start();
time.join();
tim.join();
}
public static class ProducerConsumer {
LinkedList<Integer> L = new LinkedList<>();
int X = 2;
public void produce() throws InterruptedException
{
int V = 0;
while (true) {
synchronized (this)
{
while (L.size() == X)
wait();
System.out.println("Producer produced:"
+ V);
L.add(V++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (L.size() == 0)
wait();
int val = L.removeFirst();
System.out.println("Consumer consumed:"
+ val);
Thread.sleep(1000);
}
}
}
}
}
Comments
Leave a comment