Inter-thread communication in Java allows multiple threads to coordinate and work together. It is mainly achieved using wait(), notify(), and notifyAll() methods of the Object class.
Watch how the Producer and Consumer coordinate. Notice they never work at the exact same time.
wait() → Thread releases lock and waitsnotify() → Wakes one waiting threadnotifyAll() → Wakes all waiting threads
// Shared resource class using inter-thread communication
class Data {
int value;
boolean hasData = false;
synchronized void produce(int v) {
while (hasData) {
try {
wait();
} catch (InterruptedException e) {}
}
value = v;
hasData = true;
System.out.println("Produced: " + value);
notify();
}
synchronized void consume() {
while (!hasData) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Consumed: " + value);
hasData = false;
notify();
}
}
// Producer thread
class Producer extends Thread {
Data d;
Producer(Data d) {
this.d = d;
}
public void run() {
for (int i = 1; i <= 5; i++) {
d.produce(i);
}
}
}
// Consumer thread
class Consumer extends Thread {
Data d;
Consumer(Data d) {
this.d = d;
}
public void run() {
for (int i = 1; i <= 5; i++) {
d.consume();
}
}
}
// Main class to start threads
public class InterThreadDemo {
public static void main(String[] args) {
Data d = new Data();
new Producer(d).start();
new Consumer(d).start();
}
}
Producer generates a value and notifies the consumer. Consumer waits until data is available, consumes it, and notifies producer again. This avoids data inconsistency and CPU wastage.