Java - Threads Part 4: Thread Communication
Threads can communicate using methods like wait(), notify(), and notifyAll().
Examples and Explanation
Wait and Notify
class SharedResource {
public synchronized void produce() throws InterruptedException {
System.out.println("Producing...");
wait();
System.out.println("Resumed!");
}
public synchronized void consume() {
System.out.println("Consuming...");
notify();
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
try {
resource.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumer = new Thread(resource::consume);
producer.start();
consumer.start();
}
}
Explanation: wait() pauses the thread until another thread calls notify().
Using notifyAll()
public synchronized void notifyAllThreads() {
notifyAll();
}
Explanation: This method wakes all threads waiting on an object's monitor.