Inter-thread Communication in Java


 

Inter-thread Communication in Java

(Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class:

  • 1.   wait()
  • 2.   notify()
  • 3.   notifyAll()

 


Example 01:


package com.java.Multi_threading;


//Inter-thread Communication


class SharedResource {

private final int[] buffer = new int[10];

private int count = 0;


public void produce() throws InterruptedException {

int value = 0;

while (true) {

synchronized (this) {

// Wait if the buffer is full

while (count == buffer.length) {

wait();

}


// Produce an item and add it to the buffer

System.out.println("Producing: " + value);

buffer[count++] = value++;


// Notify consumers that an item is available

notify();


// Introduce a delay for better visualization

Thread.sleep(1000);

}

}

}


public void consume() throws InterruptedException {

while (true) {

synchronized (this) {

// Wait if the buffer is empty

while (count == 0) {

wait();

}


// Consume an item from the buffer

int consumedValue = buffer[--count];

System.out.println("Consuming: " + consumedValue);


// Notify producers that space is available in the buffer

notify();


// Introduce a delay for better visualization

Thread.sleep(1000);

}

}

}

}


public class ProducerConsumerExample {

public static void main(String[] args) {

final SharedResource sharedResource = new SharedResource();


// Producer thread

Thread producerThread = new Thread(() -> {

try {

sharedResource.produce();

} catch (InterruptedException e) {

e.printStackTrace();

}

});


// Consumer thread

Thread consumerThread = new Thread(() -> {

try {

sharedResource.consume();

} catch (InterruptedException e) {

e.printStackTrace();

}

});


// Start the producer and consumer threads

producerThread.start();

consumerThread.start();

}

}

Post a Comment

0 Comments