Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Interthreaded Communication, Wait(), and Notify() Methods in Java

 

In this lesson, you will learn.

  • Interthreaded Communication
  • wait(), notify(), and notifyAll() Methods
  • Example

 

Interthreaded Communication

  1. It is the process by which multiple threads share information and coordinate their activities.
  2. It allows threads to work together, synchronize tasks, or notify one another about specific events.
  3. This is essential for concurrent programming, where multiple threads execute simultaneously and need to collaborate efficiently without running into data corruption, deadlocks, or inconsistent states.

 

Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods.

These methods are implemented as final methods in Object, so all classes have them.

1. wait() method

  • When a thread calls the wait() method on an object, it voluntarily releases the lock it holds on that object and enters the “waiting” state. It will remain in this state until another thread notifies it (using notify() or notifyAll()) on the same object.
  • Important Note: wait() can only be called from within a synchronized block or method that holds the lock on the object. Otherwise, it will throw an IllegalMonitorStateException.

2. notify() Method

  • When a thread calls the notify() method on an object, it wakes up a single thread that is waiting on that same object. If multiple threads are waiting, the JVM doesn’t guarantee which one will be awakened.
  • Important Note: Like wait(), notify() must also be called from within a synchronized block or method that holds the lock on the object.

3. notifyAll() Method:

  • The notifyAll() method wakes up all the threads that are waiting on the same object. Each of the awakened threads will then compete to re-acquire the lock on the object.
  • Important Note: Like wait() and notify(), notifyAll() must be called from within a synchronized block or method that holds the lock on the object.

     

    Example: Accessing Banking

    package interthreadedcommunication;
    
    class Banking {
    	static public int balance = 0;
    	//Method to withdraw amount
    	public synchronized void withdraw(int amount){
    		if(balance <= 0){
    			try {
    				System.out.println("Waiting for your balance to update "
    						+ "before withdrawal of $"+amount);
    				wait();
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		balance = balance - amount;
    		System.out.println("Withdrawal successful. "
    				+ "The current balance is: $"+balance);
    	}
    	//Method to deposit amount
    	public synchronized void deposit(int amount){
    		System.out.println("We are depositing the amount $"+amount);
    		balance = balance + amount;
    		notify(); //Notify thread after depositing money
    	}	
    }
    //Creating a thread to withdraw money
    class BankThread1 extends Thread {
    	Banking banking;
    
    	public BankThread1(Banking banking) {
    		this.banking = banking;
    	}
    
    	@Override
    	public void run() {
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		banking.withdraw(1500);
    	}
    }
    
    //Creating a thread to deposit money
    class BankThread2 extends Thread {
    	Banking banking;
    
    	public BankThread2(Banking banking) {
    		this.banking = banking;
    	}
    
    	@Override
    	public void run() {
    		try {
    			Thread.sleep(2000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		banking.deposit(5000);
    	}
    }
    
    public class WaitNotifyExample {
    	public static void main(String[] args) {
    		Banking banking = new Banking();
    
    		BankThread1 bThread1 = new BankThread1(banking);
    		BankThread2 bThread2 = new BankThread2(banking);
    		//Start both the thread
    		bThread1.start(); 
    		bThread2.start();
    	}
    
    }
    
    

    Output

    Waiting for your balance to update before withdrawal of $1500
    We are depositing the amount $5000
    Withdrawal successful. The current balance is: $3500
    

     

    Key Points to Remember:

    • wait(), notify(), and notifyAll() must be called within a synchronized block or method on the object being waited on/notified.
    • Threads call wait() to pause their execution and release the lock.
    • Threads call notify() or notifyAll() to signal waiting threads that a condition might have changed.
    • Waiting threads need to re-acquire the lock after being notified before they can resume execution.
    • It’s common practice to use wait() within a while loop that checks the condition. This is to handle “spurious wakeups” (where a thread might be woken up without a notify() call) and to re-verify the condition after re-acquiring the lock.

    Inter-threaded communication is a fundamental concept in concurrent programming, allowing you to build more complex and efficient applications by coordinating the actions of multiple threads. Understanding and correctly using wait(), notify(), and notifyAll() is crucial for achieving this in Java.

     

     

     

     

     


    End of the lesson….enjoy learning

     

     

    Student Ratings and Reviews

     

     

     

    There are no reviews yet. Be the first one to write one.

     

     

    Submit a Review