🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Inter-Thread Communication in Java  


Introduction
  • Inter-Thread Communication (ITC) is a mechanism that allows threads to communicate with each other while sharing resources.
  • It ensures that threads cooperate instead of running blindly and causing inconsistent data (race conditions).
  • Java provides three main methods in the Object class to achieve ITC:
    1. wait():
      • Makes the current thread wait until another thread calls notify() or notifyAll() on the same object.
      • It releases the lock while waiting.
    2. notify():
      • Wakes up one waiting thread on the object’s monitor. The awakened thread will continue after acquiring the lock.
    3. notifyAll():
      • Wakes up all threads waiting on the object’s monitor. Each thread will compete for the lock.
  • Program:
    class MovieEarning extends Thread
    {
        int total_earning = 0;
        int ticket_price = 250; // Price of one movie ticket
        int tickets_sold = 10;  // Total tickets sold
    
        @Override
        public void run()
        {
            synchronized(this)
            {
                total_earning = ticket_price * tickets_sold;
    
                // Notify main thread that calculation is done
                this.notify();
            }
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args) throws InterruptedException
        {
            MovieEarning me = new MovieEarning();
            me.start();
    
            synchronized(me)
            {
                me.wait(); // Wait until MovieEarning thread notifies
                System.out.println("Total movie earnings: Rs. " + me.total_earning);
            }
        }
    }

Key Points to Remember:
  • Only the thread holding the object’s lock can call wait(), notify(), or notifyAll().
  • wait() releases the lock, allowing other threads to acquire it.
  • notify() / notifyAll() do not release the lock immediately; the awakened thread runs only after the lock is free.
  • Inter-Thread Communication (ITC) is primarily for coordinating threads and avoiding race conditions, but does not directly avoid deadlocks.
  • Deadlocks can still occur if multiple threads acquire multiple locks in the wrong order.