Thursday, August 24, 2017

Multithreading.. Synchroniation example


public class Thread12 extends Thread{

 int amount=10000;
 synchronized void withdrawl(int amount)
 {
  if (this.amount<amount)
  {
   System.out.println("Insufficient Balance "+this.amount);
  }
  try {
   wait();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   
  }
  this.amount-=amount;
  System.out.println(" Balance Left "+this.amount);
 }

 synchronized void deposit(int amount)
 {
  this.amount+=amount;
  System.out.println("Amount deposited, Balance"+this.amount);
  notify();
 }


 public static void main(String[] args) {
  
   final Thread12 t2=new Thread12();
  
  new Thread(){
   public void run(){t2.withdrawl(15000);}
  }.start();

  new Thread(){
   public void run(){t2.deposit(5000);}
  }.start();
 }

}

No comments:

Post a Comment