Inter-thread communication in Java allows threads to coordinate their actions by sharing
information and managing access to shared resources. It’s essential for building efficient,
synchronized multi-threaded applications.
🔄 What Is Inter-thread Communication?
Inter-thread communication is a mechanism where one thread pauses its execution in a critical
section and allows another thread to enter that section. This avoids polling, which wastes CPU
cycles by repeatedly checking conditions.
🧰 Core Methods for Communication
Java provides three key methods from the Object class to facilitate inter-thread communication:
Method Description
wait()
Causes the current thread to wait until another thread calls notify() or
notifyAll() on the same object.
notify() Wakes up one thread that is waiting on the object’s monitor.
notifyAll() Wakes up all threads waiting on the object’s monitor.
These methods must be called within a synchronized block or method, ensuring mutual
exclusion.
📦 Example Scenario: Producer-Consumer Problem
In this classic problem:
Producer thread generates data and adds it to a shared buffer.
Consumer thread retrieves data from the buffer.
If the buffer is full, the producer waits; if empty, the consumer waits.
java
synchronized(buffer) {
while ([Link]()) {
[Link]();
}
[Link]();
[Link]();
}
🚫 Why Not Polling?
Polling involves repeatedly checking a condition in a loop, which:
Wastes CPU cycles
Slows down execution
Is inefficient compared to event-driven communication
✅ Benefits of Inter-thread Communication
Efficient resource sharing
Reduced CPU usage
Better synchronization
Avoids deadlocks and race conditions
//Synchronization of Thread
import [Link].*;
import [Link].*;
class one extends Thread
{
public void run()
{
[Link]();
}
}
class synclass
{
public static synchronized void view()
{
for(int i=1;i<=10;i++)
[Link](i);
}
}
class syn
{
public static void main(String args[]) throws IOException
{
one t1= new one();
one t2= new one();
[Link]();
[Link]();
}
}