Write a program in java to demonstrate wait(), notify() and notifyAll() method?

class Customer1

{

      int amount=10000;

      public synchronized void withdraw(int amount)

      {

            if(this.amount<amount)

            {

                  System.out.println("Less Balance Waiting For Deposit");

                  try

                  {

                        wait();

                  }

                  catch(Exception e)

                  {}

            }

            this.amount-=amount;

            System.out.println("Withdraw Completed _ _ _ ");

      }

      public synchronized void deposit(int amount)

      {

            System.out.println("Going To Deposit.");

            this.amount+=amount;

            System.out.println("Deposit Completed _ _ _ ");

            notify();

      }

}

class Thread1 extends Thread

{

      Customer1 c;

      public Thread1(Customer1 c)

      {

            super();

            this.c=c;

      }

      public void run()

      {

            c.withdraw(15000);

      }

}

class Thread2 extends Thread

{

      Customer1 c;

      public Thread2(Customer1 c)

      {

            super();

            this.c=c;

      }

      public void run()

      {

            c.deposit(10000);

      }

}

public class InterThreadWithoutAnonymousClass

{

      public static void main(String arg[])

      {

            Customer1 c=new Customer1();

            Thread1 t1=new Thread1(c);

            Thread2 t2=new Thread2(c);

            t1.start();

            t2.start();

      }

}

Wait(), Notify() and NotifyAll() method.PNG

, , , , , , , ,

Leave a Reply