← Back to Chapters

Inter-Thread Communication

? Inter-Thread Communication

? Quick Overview

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.

? Key Concepts

  • Threads communicate using shared objects
  • Methods belong to Object class, not Thread
  • Used inside synchronized blocks only
  • Helps avoid busy waiting

? Interactive Simulation

Watch how the Producer and Consumer coordinate. Notice they never work at the exact same time.

?‍?
Producer
Idle
Shared Object
?
Data: Empty
?
Consumer
Idle
System Idle. Click Start.

? Syntax & Theory

  • wait() → Thread releases lock and waits
  • notify() → Wakes one waiting thread
  • notifyAll() → Wakes all waiting threads

? Code Example — Producer Consumer

? View Code Example
// 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();
}
}
? View Code Example
// 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);
}
}
}
? View Code Example
// 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();
}
}
}
? View Code Example
// 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();
}
}

? Output / Explanation

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.

✅ Tips & Best Practices

  • Always call wait/notify inside synchronized blocks
  • Prefer while loop instead of if condition
  • Use notifyAll for multiple waiting threads
  • Avoid calling wait on Thread object

? Try It Yourself

  • Modify program to use notifyAll()
  • Add delay using Thread.sleep()
  • Implement multiple producers and consumers