Interview question
What are wait(), notify(), and notifyAll() methods? How do they enable thread communication? wait(), notify() और notifyAll() methods क्या हैं? Thread communication कैसे करते हैं?
Answer
wait(), notify(), and notifyAll() enable inter-thread communication. wait() makes thread wait for notification, notify() wakes one thread, notifyAll() wakes all waiting threads. Must be used within synchronized block.
// Producer-Consumer Example
public class ProducerConsumer {
private int value = 0;
private boolean produced = false;
// Producer thread
public synchronized void produce() {
while (produced) {
try {
wait(); // Wait if already produced
} catch (InterruptedException e) {}
}
value = (int) (Math.random() * 100);
System.out.println('Produced: ' + value);
produced = true;
notify(); // Wake up consumer
}
// Consumer thread
public synchronized void consume() {
while (!produced) {
try {
wait(); // Wait until produced
} catch (InterruptedException e) {}
}
System.out.println('Consumed: ' + value);
produced = false;
notify(); // Wake up producer
}
}
public class Main {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
pc.produce();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
pc.consume();
}
}).start();
}
}
// How it works:
// 1. Producer produces value, calls notify()
// 2. Consumer wakes up, consumes
// 3. Consumer calls notify() to wake producer
// 4. Process repeats
// wait() vs sleep():
// wait(): Releases lock, thread waits
// sleep(): Keeps lock, thread sleeps
// Comparison: notify() vs notifyAll()
notify(); // Wakes one thread (unpredictable)
notifyAll(); // Wakes all threads (safer)
// Best Practice: Use BlockingQueue (easier)
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueDemo {
private BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
public void produce() throws InterruptedException {
queue.put(100); // Automatically handles waiting
}
public int consume() throws InterruptedException {
return queue.take(); // Automatically handles waiting
}
}Thread Communication:
wait():
- Current thread को wait करता है
- Lock release करता है
- notify() का wait करता है
notify():
- Waiting thread को जगाता है
- Lock release होने का wait करता है
notifyAll():
- सभी waiting threads को जगाता है
- Safer option
Rules:
1. synchronized block में use करना
2. wait() always try-catch में
3. while loop में check करो
Best Practice:
BlockingQueue use करो (simpler)
Manual wait/notify नहींWas this answer clear?