Dis Practical-8

import java.util.LinkedList;
import java.util.Queue;

class Producer extends Thread {
    private final Queue<Integer> buffer;
    private final int capacity;

    public Producer(Queue<Integer> buffer, int capacity) {
        this.buffer = buffer;
        this.capacity = capacity;
    }

    @Override
    public void run() {
        while (true) {
            try {
                produce();
                Thread.sleep((int) (Math.random() * 2000)); // Random sleep to simulate production time
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void produce() throws InterruptedException {
        synchronized (buffer) {
            while (buffer.size() == capacity) {
                System.out.println("Buffer is full, waiting for consumer to consume.");
                buffer.wait(); // Wait if buffer is full
            }

            int item = (int) (Math.random() * 100); // Generate a random item
            buffer.add(item); // Add the item to the buffer
            System.out.println("Produced: " + item);

            buffer.notifyAll(); // Notify consumers that they can consume
        }
    }
}

class Consumer extends Thread {
    private final Queue<Integer> buffer;

    public Consumer(Queue<Integer> buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        while (true) {
            try {
                consume();
                Thread.sleep((int) (Math.random() * 3000)); // Random sleep to simulate consumption time
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void consume() throws InterruptedException {
        synchronized (buffer) {
            while (buffer.isEmpty()) {
                System.out.println("Buffer is empty, waiting for producer to produce.");
                buffer.wait(); // Wait if buffer is empty
            }

            int item = buffer.remove(); // Consume the item from the buffer
            System.out.println("Consumed: " + item);

            buffer.notifyAll(); // Notify producers that they can produce
        }
    }
}

public class ProducerConsumer {
    public static void main(String[] args) {
        Queue<Integer> buffer = new LinkedList<>();
        int capacity = 5;

        // Create producer and consumer threads
        Thread producer1 = new Producer(buffer, capacity);
        Thread producer2 = new Producer(buffer, capacity);
        Thread consumer1 = new Consumer(buffer);
        Thread consumer2 = new Consumer(buffer);

        // Start threads
        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top