|
| 1 | +class ItemQueue { |
| 2 | + int item; |
| 3 | + boolean valueSet = false; |
| 4 | + |
| 5 | + synchronized int getItem() { |
| 6 | + while (!valueSet) |
| 7 | + try { |
| 8 | + wait(); |
| 9 | + } catch (InterruptedException e) { |
| 10 | + System.out.println("InterruptedException caught"); |
| 11 | + } |
| 12 | + System.out.println("Consummed:" + item); |
| 13 | + valueSet = false; |
| 14 | + try { |
| 15 | + Thread.sleep(1000); |
| 16 | + } catch (InterruptedException e) { |
| 17 | + System.out.println("InterruptedException caught"); |
| 18 | + } |
| 19 | + notify(); |
| 20 | + return item; |
| 21 | + } |
| 22 | + |
| 23 | + synchronized void putItem(int item) { |
| 24 | + while (valueSet) |
| 25 | + try { |
| 26 | + wait(); |
| 27 | + } catch (InterruptedException e) { |
| 28 | + System.out.println("InterruptedException caught"); |
| 29 | + } |
| 30 | + this.item = item; |
| 31 | + valueSet = true; |
| 32 | + System.out.println("Produced: " + item); |
| 33 | + try { |
| 34 | + Thread.sleep(1000); |
| 35 | + } catch (InterruptedException e) { |
| 36 | + System.out.println("InterruptedException caught"); |
| 37 | + } |
| 38 | + notify(); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +class Producer implements Runnable { |
| 43 | + ItemQueue itemQueue; |
| 44 | + |
| 45 | + Producer(ItemQueue itemQueue) { |
| 46 | + this.itemQueue = itemQueue; |
| 47 | + new Thread(this, "Producer").start(); |
| 48 | + } |
| 49 | + |
| 50 | + public void run() { |
| 51 | + int i = 0; |
| 52 | + while (true) { |
| 53 | + itemQueue.putItem(i++); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +class Consumer implements Runnable { |
| 59 | + ItemQueue itemQueue; |
| 60 | + |
| 61 | + Consumer(ItemQueue itemQueue) { |
| 62 | + this.itemQueue = itemQueue; |
| 63 | + new Thread(this, "Consumer").start(); |
| 64 | + } |
| 65 | + |
| 66 | + public void run() { |
| 67 | + while (true) { |
| 68 | + itemQueue.getItem(); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +class ProducerConsumer { |
| 74 | + public static void main(String args[]) { |
| 75 | + ItemQueue itemQueue = new ItemQueue(); |
| 76 | + new Producer(itemQueue); |
| 77 | + new Consumer(itemQueue); |
| 78 | + } |
| 79 | + |
| 80 | + /* Output: |
| 81 | + Produced: 0 |
| 82 | + Consummed:0 |
| 83 | + Produced: 1 |
| 84 | + Consummed:1 |
| 85 | + Produced: 2 |
| 86 | + Consummed:2 |
| 87 | + Produced: 3 |
| 88 | + Consummed:3 |
| 89 | + Produced: 4 |
| 90 | + Consummed:4 |
| 91 | + .... |
| 92 | + */ |
| 93 | +} |
0 commit comments