Thursday, 23 August 2018

Synchronization in Java: wait() and notify




                       










Program (waitnotify.java)
class Customer
{  
  int amount=10000;  
  
  synchronized void withdraw(int amount)
   {  
     System.out.println("going to withdraw...");  
  
     if(this.amount<amount)
      {  
       System.out.println("Less balance; waiting for deposit...");  
       try{wait();}
       catch(Exception e){}  
      }  
     this.amount=this.amount-amount;  
     System.out.println("withdraw completed...");  
   }  
  
  synchronized void deposit(int amount)
   {  
     System.out.println("going to deposit...");  
     this.amount=this.amount+amount;  
     System.out.println("deposit completed... ");  
     notify();  
   }  
}  
  
class waitnotify
{  
  public static void main(String args[])
   {  
     Customer c=new Customer();  
     
     new Thread()
      {  
        public void run()
         {c.withdraw(15000);}
      }.start();  
     
     new Thread()
      {  
        public void run()
         {c.deposit(10000);}  
      }.start();  
  
   }

}  
  
Output:
parag@parag-Inspiron-N4010:~/Desktop/progbythread$ javac waitnotify.java 
parag@parag-Inspiron-N4010:~/Desktop/progbythread$ java waitnotify
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed... 
withdraw completed...




                    

No comments:

Post a comment