//the key to synchronization is the concept of minitor(semaphore).a monitor is an object that
//is used to mutually exclusive lock or mutex.
//this example uses synchronized methods
class balance
{
 private int amount;
 balance(int n)
 {
  amount=n;
 }
//if a method is synchronized then only one thread can enter it the others have to wait
//remove this synchronized key word and check what happens and use it
synchronized void withdraw(int n)
 {
  if(amount>n)
   {
   try{
     Thread.sleep(1000);
     }catch(InterruptedException ie){}
    amount=amount-n;
   }   
} 
 void display()
 {
  System.out.println(amount);
  }
}
class counters implements Runnable
{
 Thread t;
 int draw;
 balance b;  
 
 counters(String s,balance temp,int d) 
 {
  draw=d;
  b=temp; 
  t=new Thread(this,s);
  t.start();
  }
 public void run()
  {
   b.withdraw(draw);
   b.display();
  }
}
class Sync 
{
 public static void main(String s[])
  {
   balance b=new balance(1000);
   //create the counter objects one by one 
   counters c1=new counters("counter1",b,100); 
   //counters c2=new counters("counter2",b,500);
   //counters c3=new counters("counter3",b,600); 
  }
}
output:
900
0 comments:
Post a Comment