标签:
1 public class SynchronizedClass extends Thread{ 2 private Account account; 3 private double drawbalance; 4 Object obj; 5 public SynchronizedClass(String name,Account account,double drawbalance,Object obj){ 6 super(name); 7 this.account=account; 8 this.drawbalance=drawbalance; 9 this.obj=obj; 10 //start(); 11 } 12 public void run(){ 13 try{sleep(100);}catch(Exception e){} 14 synchronized(obj){ 15 if(drawbalance>account.getBalance()){ 16 System.out.println("余额不足!"); 17 }else{ 18 System.out.println("吐钱成功!"); 19 try{ 20 sleep(100); 21 System.out.println("取钱:"+drawbalance); 22 account.setBalance(account.getBalance()-drawbalance); 23 System.out.println("余额为:"+account.getBalance()); 24 }catch(Exception e){ 25 System.out.println(e); 26 } 27 } 28 } 29 30 31 } 32 public static void main(String[] args){ 33 34 Object o=new Object();//传到了两个线程中,保证了是同一个锁。 35 Account a=new Account("刘腾",100000); 36 new SynchronizedClass("A线程",a,100000,o).start(); 37 new SynchronizedClass("B线程",a,10000,o).start(); 38 } 39 } 40 41 //账户 42 class Account { 43 private String name; 44 private double balance; 45 public Account(){} 46 public Account(String name,double balance){ 47 this.name=name; 48 this.balance=balance; 49 } 50 public void setName(String name){ 51 this.name=name; 52 } 53 public void setBalance(double balance){ 54 this.balance=balance; 55 } 56 public String getName(){ 57 return name; 58 } 59 public double getBalance(){ 60 return balance; 61 } 62 63 /* 64 public boolean equals(Object obj){ 65 if(this==obj)return true; 66 if(obj==null)return false; 67 if(getClass()!=obj.getClass())return false; 68 Account other =(Account) obj; 69 if(other.name==name&&other.balance==balance)return true; 70 else return false; 71 } 72 */ 73 }
标签:
原文地址:http://www.cnblogs.com/teng-IT/p/4445558.html