您好,登錄后才能下訂單哦!
- class Thread1 extends Thread
- {
- private MasterCard mc;//將mc類對象傳入作為成員變量
- public Thread1(MasterCard mc)
- {
- this.mc = mc;
- }
- public void run()
- {
- mc.charge1000();//調用synchronized方法,相當于鎖住的是引用該方法的類對象mc本身
- // mc.charge();//單線程時run方法內部相當于調用對象mc的方法
- }
- }
- class Thread2 extends Thread
- {
- private MasterCard mc;
- public Thread2(MasterCard mc)
- {
- this.mc = mc;
- }
- public void run()
- {
- mc.printMoney();
- mc.charge2000();
- }
- }
- public class MasterCard
- {
- int money = 10000;
- public synchronized void charge2000()//修飾方法,相當于鎖住的是引用該方法的類對象本身
- {
- // synchronized(this)
- // {
- this.money -= 2000;
- System.out.println("取2000后余額:" + this.money);
- // }
- }
- public void printMoney()
- {
- System.out.println("取2000前余額:" + this.money);
- }
- public synchronized void charge1000()
- {
- // synchronized(this)
- // {
- this.money -= 1000;
- System.out.println("取1000后余額:" + this.money);
- // }
- }
- public static void main(String[] args)
- {
- MasterCard mc = new MasterCard();
- Thread1 t1 = new Thread1(mc);
- t1.start();
- Thread2 t2 = new Thread2(mc);
- t2.start();
- }
- public void charge()
- {
- synchronized (this)
- {
- System.out.println("取款1000前:" + money);
- money -= 1000;
- System.out.println("余額:" + money);
- }
- }
- // public void charge()
- // {
- // System.out.println("取款前:" + money);
- // money -= 1000;
- // System.out.println("余額:" + money);
- // }
- //
- }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。