1.

How Java Threads communicate with each other?

Answer»

Inter-thread communication involves the communication of Java threads with each other. The three methods are Java that are used to IMPLEMENT inter-thread communication are given as follows:

  • wait()

This method causes the CURRENT thread to release the lock. This is done until a specific amount of time has passed or another thread calls the notify() or notifyAll() method for this OBJECT.

  • notify()

This method wakes a SINGLE thread out of multiple threads on the current object’s monitor. The choice of thread is arbitrary.

  • notifyAll()

This method wakes up all the threads that are on the current object’s monitor.

A program that demonstrates inter-thread communication in Java is given as follows:

class BankCustomer {      int balAmount = 10000;      synchronized void withdrawMoney(int amount)    {        System.out.println("Withdrawing money");          balAmount -= amount;          System.out.println("The balance amount is: " + balAmount);      }    synchronized void depositMoney(int amount)    {        System.out.println("Depositing money");          balAmount += amount;          System.out.println("The balance amount is: " + balAmount);          notify();      } }   public class Demo {      public static void main(String args[])    {        final BankCustomer cust = new BankCustomer();          new Thread()        {            public void run()            {                cust.withdrawMoney(5000);            }        }.start();          new Thread()        {            public void run()            {                cust.depositMoney(2000);            }        }.start();      } }

The output of the above program is as follows:

Withdrawing money The balance amount is: 5000 Depositing money The balance amount is: 7000


Discussion

No Comment Found