スレッド:synchronizedメソッドsynchronizedメソッド
8468 ワード
- 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);
- // }
- //
-
- }
本文は“空は痕跡がありませんが私は飛んだことがあります”のブログから出て、転載して作者と連絡してください!