Thread Communication
Thread communication refers to the mechanism by which threads can communicate and coordinate their actions. Java provides three key methods from the Object class to facilitate thread communication: wait(), notify(), and notifyAll(). These methods are used in conjunction with synchronization to ensure proper coordination between threads.
Key Methods for Thread Communication
wait():- Causes the current thread to release the lock and enter the waiting state until another thread invokes
notify()ornotifyAll()on the same object. - Must be called within a synchronized block or method.
- Causes the current thread to release the lock and enter the waiting state until another thread invokes
notify():- Wakes up a single thread that is waiting on the object's monitor. The awakened thread will resume execution after acquiring the lock.
notifyAll():- Wakes up all threads that are waiting on the object's monitor. Only one thread will acquire the lock and continue execution.
Example of Thread Communication
The following example demonstrates how threads can communicate using wait(), notify(), and notifyAll():
class SharedResource {
private boolean flag = false;
public synchronized void produce() {
try {
while (flag) {
wait(); // Wait until the consumer consumes
}
System.out.println("Producing...");
flag = true;
notify(); // Notify the consumer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void consume() {
try {
while (!flag) {
wait(); // Wait until the producer produces
}
System.out.println("Consuming...");
flag = false;
notify(); // Notify the producer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadCommunicationExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.produce();
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource.consume();
}
});
producer.start();
consumer.start();
}
}
Output:
Producing...
Consuming...
Producing...
Consuming...
...
Best Practices for Thread Communication
- Always use
wait(),notify(), andnotifyAll()within synchronized blocks or methods. - Use
notify()when only one thread needs to be awakened andnotifyAll()when multiple threads are waiting. - Avoid using
wait()in a loop without a condition check to prevent spurious wakeups.
