Inter-thread communication in Java

In the given tutorial, we are going to learn about Inter-Thread communication in Java.

Allowing multiple synchronized threads to communicate with each other and maintaining one Thread object execution at a time (with multiple thread objects in a row) is known as Inter-Thread communication in Java. This is also known as Thread safe operation or Thread synchronization.

synchronized keyword implicitly uses three methods for Inter-thread communication. All the classes can aquire this methods because they belong to Object class. They all are declared as final and must be used in a synchronized block only. Following are those :

  1. public void wait() : This method is used to send a current thread object into waiting state, till another thread invokes the notify() method or notifyAll() method for this object.
  2. public void notify() : This method is used to send a single thread object which is in waiting state into running state.
  3. public void notifyAll() : This method is used to send multiple thread objects which are in waiting state into  running state.

 

Program :

Let’s see a program of inter-thread. Below is the Java code:

package java;

class MobileRecharge
{
 int wallet = 400;

 //method to re-charge mobile
 synchronized void rechargeOf(int amount)
 {
  //if wallet money is less, then it will wait for adding money in wallet
  if(wallet<amount)
  {
   System.out.println("less money in wallet, waiting for addition of money...");
   try
   {
    wait();
   }
   catch(Exception e)
   {
   }
  }
  //if money is sufficient then recharge will be done & amount will be debited from wallet
  wallet-=amount;
  System.out.println("Recharge is successful...!!!")
  System.out.println("Remaining money in wallet is : "+wallet);
 }

 //method for adding money into the wallet
 synchronized void addingMoneyInWallet(int amount)
 {
  wallet+=amount;
  System.out.println("Money added in wallet...");
  notify();
 }

}

//main class
class ThreadExample
{
 public static void main(String[] args)
 {
  final MobileRecharge mr = new MobileRecharge();

  new Thread()
  {
   public void run()
   {
    //recharging mobile
    mr.rechargeOf(500);
   }
  }.start();

  new Thread()
  {
   public void run()
   {
    //adding money into wallet
    mr.addingMoneyInWallet(500);
   }
  }.start();

 }

}

 

Output :

The output of the above program will be :

Less money in wallet, waiting for addition of money...
Money added in wallet...
Recharge is successful...!!!
Remaining money in wallet is : 400

 

Leave a Reply

Your email address will not be published. Required fields are marked *