class Buffer { private int[] buffer; private int count = 0, in = 0, out = 0, size; public Buffer(int size) { this.size = size; buffer = new int[size]; System.out.println("Buffer initialized with size: " + size); } public synchronized void produce(int item) throws InterruptedException { while (count == size) { System.out.println("Buffer is full, producer is waiting..."); wait(); } buffer[in] = item; in = (in + 1) % size; count++; System.out.println("Produced: " + item + " | Buffer count: " + count); notifyAll(); } public synchronized int consume() throws InterruptedException { while (count == 0) { System.out.println("Buffer is empty, consumer is waiting..."); wait(); } int item = buffer[out]; out = (out + 1) % size; count--; System.out.println("Consumed: " + item + " | Buffer count: " + count); notifyAll(); return item; } } class Producer implements Runnable { private Buffer buffer; private int maxItems; public Producer(Buffer buffer, int maxItems) { this.buffer = buffer; this.maxItems = maxItems; } @Override public void run() { try { for (int i = 1; i <= maxItems; i++) { System.out.println("Producer trying to produce: " + i); buffer.produce(i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Producer interrupted."); } } } class Consumer implements Runnable { private Buffer buffer; public Consumer(Buffer buffer) { this.buffer = buffer; } @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { int item = buffer.consume(); System.out.println("Consumer consumed: " + item); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Consumer interrupted."); } } } public class six { public static void main(String[] args) throws InterruptedException { int bufferSize = 5, maxItemsToProduce = 10; Buffer buffer = new Buffer(bufferSize); Thread producerThread = new Thread(new Producer(buffer, maxItemsToProduce)); Thread consumerThread = new Thread(new Consumer(buffer)); producerThread.start(); consumerThread.start(); producerThread.join(); consumerThread.interrupt(); consumerThread.join(); System.out.println("Process completed."); } }