Advertisement
Guest User

thread safety

a guest
Oct 31st, 2014
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. class Test1
  2. {
  3.  
  4.     public static void main(String args[])
  5.     {
  6.         Thread1 a=new Thread1(300);
  7.         Thread2 b=new Thread2(200);
  8.        
  9.         Thread one=new Thread(a);
  10.         Thread two=new Thread(b);
  11.         try
  12.         {
  13.             one.start();
  14.            two.start();
  15.         one.join();
  16.             two.join();
  17.         }
  18.         catch(InterruptedException e)
  19.         {
  20.         }
  21.             //the parameters in the start method contains the amount to withdraw
  22.     System.out.println(" The current balance is now = "+ Account.curr_bal);
  23.        
  24.     }    
  25.    
  26.    
  27. }
  28.  
  29.  
  30. class Thread1 implements Runnable
  31. {
  32.     int withdrawal;
  33.     Thread1(int amt)
  34.     {
  35.         withdrawal=amt;
  36.     }
  37.    
  38.     public void run()
  39.     {
  40.       Account obj1=new Account();
  41.       obj1.withdraw(withdrawal);
  42.       System.out.println(" Withdrawal complete successfully done by Thread1");
  43.           }
  44. }
  45.  
  46. class Thread2 implements Runnable
  47. {
  48.     int withdrawal;
  49.     Thread2(int amt)
  50.     {
  51.         withdrawal=amt;
  52.     }
  53.    
  54.     public void run()
  55.     {
  56.         Account obj1=new Account();
  57.         obj1.withdraw(withdrawal);
  58.         System.out.println(" Withdrawal complete successfully done by Thread2");
  59.         }
  60. }
  61.  
  62. class Account
  63. {
  64.     static int curr_bal=400;
  65.     void withdraw(int amt)
  66.     {
  67.         if(curr_bal>amt)
  68.         {
  69.             try
  70.             {
  71.                 Thread.sleep(1000);
  72.             }
  73.             catch(InterruptedException e)
  74.             {
  75.             }
  76.             curr_bal=curr_bal-amt;
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement