1 public class SynchronizedClass1 extends Thread{ 2 private Account account; 3 private double drawbalance; 4 public SynchronizedClass1(String name,Account account,double drawbalance){ 5 super(name); 6 this.account=account; 7 this.drawbalance=drawbalance; 8 start(); 9 10 } 11 public void run(){ 12 for(int i=0;i<20;i++){ 13 try{sleep(1000);}catch(Exception e){} 14 account.draw(drawbalance);} 15 } 16 public static void main(String[] args){ 17 Account a=new Account("刘腾",100000); 18 new SynchronizedClass1("A线程",a,100); 19 Thread rt=new Thread(new RunnableClass(a)); 20 rt.setName("B线程"); 21 rt.start(); 22 } 23 } 24 //账户 25 class Account { 26 private String name; 27 private double balance; 28 public Account(){} 29 public Account(String name,double balance){ 30 this.name=name; 31 this.balance=balance; 32 } 33 public void setName(String name){ 34 this.name=name; 35 } 36 public void setBalance(double balance){ 37 this.balance=balance; 38 } 39 public String getName(){ 40 return name; 41 } 42 public double getBalance(){ 43 return balance; 44 } 45 public boolean equals(Object obj){ 46 if(this==obj)return true; 47 if(obj!=null)return false; 48 if(getClass()!=obj.getClass())return false; 49 Account other =(Account) obj; 50 if(other.name==name&&other.balance==balance)return true; 51 else return false; 52 } 53 public synchronized void draw(double drawbalance ){ 54 if(drawbalance>getBalance()){ 55 System.out.println("余额不足!"); 56 }else{ 57 System.out.println("吐钱成功!"); 58 try{ 59 Thread.sleep(1000); 60 setBalance(getBalance()-drawbalance); 61 System.out.println("余额为:"+getBalance()); 62 }catch(Exception e){ 63 System.out.println(e); 64 } 65 } 66 } 67 } 68 class RunnableClass implements Runnable{ 69 private Account account; 70 //private double drawbalance; 71 public RunnableClass(Account account){ 72 this.account=account; 73 } 74 public void run(){ 75 for(int k=0;k<15;k++){ 76 try{Thread.sleep(1000); 77 System.out.println(account.getBalance()); 78 }catch(Exception e){} 79 } 80 } 81 }
问题:一个Account实例,传到两个线程中,一个线程(1)执行它的同步代码方法,另一个线程(2)执行它的普通方法。我在同步代码块中让其线程进入休眠。按理说只要进入同步代码块,这个类就被加锁了,另外一个线程不应该执行撒。为什么就在(1)休眠的状态下,(2)却执行了?求教!!!