|
| 1 | +class SharedBuffer { |
| 2 | + private int data; |
| 3 | + private boolean hasData = false; |
| 4 | + |
| 5 | + // Producer method |
| 6 | + public synchronized void produce(int value) { |
| 7 | + try { |
| 8 | + while (hasData) { |
| 9 | + wait(); // wait if data is not yet consumed |
| 10 | + } |
| 11 | + data = value; |
| 12 | + hasData = true; |
| 13 | + System.out.println("Produced: " + data); |
| 14 | + notify(); // notify consumer |
| 15 | + } catch (InterruptedException e) { |
| 16 | + e.printStackTrace(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + // Consumer method |
| 21 | + public synchronized void consume() { |
| 22 | + try { |
| 23 | + while (!hasData) { |
| 24 | + wait(); // wait if there's no data to consume |
| 25 | + } |
| 26 | + System.out.println("Consumed: " + data); |
| 27 | + hasData = false; |
| 28 | + notify(); // notify producer |
| 29 | + } catch (InterruptedException e) { |
| 30 | + e.printStackTrace(); |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class Producer extends Thread { |
| 36 | + private SharedBuffer buffer; |
| 37 | + |
| 38 | + public Producer(SharedBuffer buffer) { |
| 39 | + this.buffer = buffer; |
| 40 | + } |
| 41 | + |
| 42 | + public void run() { |
| 43 | + for (int i = 1; i <= 5; i++) { |
| 44 | + buffer.produce(i); |
| 45 | + try { |
| 46 | + Thread.sleep(500); // simulate production time |
| 47 | + } catch (InterruptedException e) { |
| 48 | + e.printStackTrace(); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +class Consumer extends Thread { |
| 55 | + private SharedBuffer buffer; |
| 56 | + |
| 57 | + public Consumer(SharedBuffer buffer) { |
| 58 | + this.buffer = buffer; |
| 59 | + } |
| 60 | + |
| 61 | + public void run() { |
| 62 | + for (int i = 1; i <= 5; i++) { |
| 63 | + buffer.consume(); |
| 64 | + try { |
| 65 | + Thread.sleep(800); // simulate consumption time |
| 66 | + } catch (InterruptedException e) { |
| 67 | + e.printStackTrace(); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +class InterThreadCommunication { |
| 74 | + public static void main(String[] args) { |
| 75 | + SharedBuffer buffer = new SharedBuffer(); |
| 76 | + |
| 77 | + Producer producer = new Producer(buffer); |
| 78 | + Consumer consumer = new Consumer(buffer); |
| 79 | + |
| 80 | + producer.start(); |
| 81 | + consumer.start(); |
| 82 | + } |
| 83 | +} |
| 84 | + |
0 commit comments