classThread1extendsThread{privateMasterCardmc;//将mc类对象传入作为成员变量publicThread1(MasterCardmc){this.mc=mc;}publicvoidrun(){mc.charge1000();//调用synchronized方法,相当于锁住的是引用该方法的类对象mc本身//mc.charge();//单线程时run方法内部相当于调用对象mc的方法}}classThread2extendsThread{privateMasterCardmc;publicThread2(MasterCardmc){this.mc=mc;}publicvoidrun(){mc.printMoney();mc.charge2000();}}publicclassMasterCard{intmoney=10000;publicsynchronizedvoidcharge2000()//修饰方法,相当于锁住的是引用该方法的类对象本身{//synchronized(this)//{this.money-=2000;System.out.println("取2000后余额:"+this.money);//}}publicvoidprintMoney(){System.out.println("取2000前余额:"+this.money);}publicsynchronizedvoidcharge1000(){//synchronized(this)//{this.money-=1000;System.out.println("取1000后余额:"+this.money);//}}publicstaticvoidmain(String[]args){MasterCardmc=newMasterCard();Thread1t1=newThread1(mc);t1.start();Thread2t2=newThread2(mc);t2.start();}publicvoidcharge(){synchronized(this){System.out.println("取款1000前:"+money);money-=1000;System.out.println("余额:"+money);}}//publicvoidcharge()//{//System.out.println("取款前:"+money);//money-=1000;//System.out.println("余额:"+money);//}//}