|
| 1 | +import java.util.LinkedList; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +public class ProducerConsumer { |
| 5 | + static private Queue<Integer> queue; // object of Queue class |
| 6 | + private int capacity; |
| 7 | + |
| 8 | + public ProducerConsumer(int cap) { |
| 9 | + queue = new LinkedList<>(); |
| 10 | + capacity = cap; |
| 11 | + } |
| 12 | + |
| 13 | + public boolean add(int item) { // for producer thread |
| 14 | + synchronized (queue) { // Queue queue() object used as MUTEX |
| 15 | + while (queue.size() == capacity) { |
| 16 | + try { |
| 17 | + queue.wait(); // wait till queue is not full |
| 18 | + } catch (InterruptedException e) { |
| 19 | + e.printStackTrace(); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + System.out.print(Thread.currentThread().getName() + " Producing: "); |
| 24 | + queue.add(item); |
| 25 | + queue.notifyAll(); // notify all threads that queue is not empty |
| 26 | + return true; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public int remove() { // for consumer thread |
| 31 | + synchronized (queue) { |
| 32 | + while (queue.size() == 0) { |
| 33 | + try { |
| 34 | + queue.wait(); // wait till queue is not empty |
| 35 | + } catch (InterruptedException e) { |
| 36 | + e.printStackTrace(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + System.out.print(Thread.currentThread().getName() + " Consuming: "); |
| 41 | + int dequeued = queue.poll(); // dequeueing |
| 42 | + queue.notifyAll(); // notify all threads that queue is not full |
| 43 | + return dequeued; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public static void main(String[] args) { |
| 48 | + System.out.println("Main Thread Starting"); |
| 49 | + ProducerConsumer ob = new ProducerConsumer(10); |
| 50 | + |
| 51 | + // Producer Threads |
| 52 | + new Thread(() -> { |
| 53 | + while (true) { |
| 54 | + System.out.println(ob.add(100) + "(size = " + queue.size() + ")"); |
| 55 | + } |
| 56 | + }, "Producer 1").start(); |
| 57 | + new Thread(() -> { |
| 58 | + while (true) { |
| 59 | + System.out.println(ob.add(100) + "(size = " + queue.size() + ")"); |
| 60 | + } |
| 61 | + }, "Producer 2").start(); |
| 62 | + |
| 63 | + // Consumer Threads |
| 64 | + new Thread(() -> { |
| 65 | + while (true) { |
| 66 | + System.out.println(ob.remove() + "(size = " + queue.size() + ")"); |
| 67 | + } |
| 68 | + }, "Consumer 1").start(); |
| 69 | + new Thread(() -> { |
| 70 | + while (true) { |
| 71 | + System.out.println(ob.remove() + "(size = " + queue.size() + ")"); |
| 72 | + } |
| 73 | + }, "Consumer 2").start(); |
| 74 | + |
| 75 | + System.out.println("Main Thread Exiting"); |
| 76 | + } |
| 77 | +} |
0 commit comments