Inter-Thread Communication: wait(), notify(), and notifyAll() πŸ“©

Inter-thread communication in Java allows threads to coordinate their execution efficiently. The wait(), notify(), and notifyAll() methods help multiple threads work together without unnecessary CPU usage.

1. Why is Inter-Thread Communication Needed? πŸ€”

Without proper communication, threads may run inefficiently, leading to race conditions, deadlocks, or wasted CPU cycles.

Real-Life Example 🍽️

A waiter (thread) waits for a chef (another thread) to prepare food. The waiter should not check the kitchen continuously but should be notified when the food is ready.

2. Using wait() and notify() πŸ”„

The wait() method makes a thread pause execution until another thread notifies it.

Example Code πŸ“

class SharedResource {
    private boolean ready = false;

    synchronized void produce() {
        try {
            System.out.println("Producing data...");
            Thread.sleep(2000);
            ready = true;
            notify(); // Notify waiting thread
        } catch (InterruptedException e) {}
    }

    synchronized void consume() {
        try {
            while (!ready) {
                System.out.println("Waiting for data...");
                wait(); // Wait for notify()
            }
            System.out.println("Consuming data...");
        } catch (InterruptedException e) {}
    }
}

public class InterThreadExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread producer = new Thread(() -> resource.produce());
        Thread consumer = new Thread(() -> resource.consume());

        consumer.start();
        producer.start();
    }
}

πŸ“Œ Key Points:

  • wait() makes a thread pause execution until notified.
  • notify() wakes up one waiting thread.
  • notifyAll() wakes up all waiting threads.

3. Using notifyAll() πŸ› οΈ

If multiple threads are waiting on the same resource, notifyAll() ensures all of them are woken up.

synchronized void produce() {
    ready = true;
    notifyAll(); // Notifies all waiting threads
}

4. Best Practices πŸ†

  • Always call wait() inside a loop to prevent spurious wakeups.
  • Use notify() if only one thread should be woken up.
  • Use notifyAll() if multiple threads may need to proceed.

5. Conclusion 🎯

  • wait(), notify(), and notifyAll() help threads coordinate execution.
  • Proper usage prevents CPU wastage and improves efficiency.
  • Always use synchronization while calling these methods to avoid IllegalMonitorStateException.

Mastering inter-thread communication improves performance and prevents concurrency issues in Java applications! πŸš€

0
Subscribe to my newsletter

Read articles from 𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”© directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”©
𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”©