Answer to Question #255403 in Java | JSP | JSF for hatipo

Question #255403

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


1
Expert's answer
2021-10-23T03:03:38-0400
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);
                }
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS