温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

线程:synchronized方法

发布时间:2020-06-30 23:03:15 来源:网络 阅读:357 作者:glblong 栏目:开发技术

 

  1. class Thread1 extends Thread 
  2.     private MasterCard mc;//将mc类对象传入作为成员变量 
  3.      
  4.     public Thread1(MasterCard mc) 
  5.     { 
  6.         this.mc = mc; 
  7.     } 
  8.      
  9.     public void run() 
  10.     { 
  11.         mc.charge1000();//调用synchronized方法,相当于锁住的是引用该方法的类对象mc本身 
  12.       //  mc.charge();//单线程时run方法内部相当于调用对象mc的方法 
  13.     } 
  14.  
  15. class Thread2 extends Thread 
  16.     private MasterCard mc; 
  17.      
  18.     public Thread2(MasterCard mc) 
  19.     { 
  20.         this.mc = mc; 
  21.     } 
  22.      
  23.     public void run() 
  24.     { 
  25.         mc.printMoney(); 
  26.         mc.charge2000(); 
  27.     } 
  28. public class MasterCard 
  29.     int money = 10000
  30.     public synchronized void charge2000()//修饰方法,相当于锁住的是引用该方法的类对象本身 
  31.     { 
  32. //        synchronized(this) 
  33. //        { 
  34.             this.money -= 2000
  35.             System.out.println("取2000后余额:" + this.money); 
  36. //        } 
  37.     } 
  38.      
  39.     public void printMoney() 
  40.     { 
  41.         System.out.println("取2000前余额:" + this.money); 
  42.     } 
  43.      
  44.     public synchronized void charge1000() 
  45.     { 
  46. //        synchronized(this) 
  47. //        { 
  48.             this.money -= 1000
  49.             System.out.println("取1000后余额:" + this.money); 
  50. //        } 
  51.     } 
  52.      
  53.     public static void main(String[] args) 
  54.     { 
  55.         MasterCard mc = new MasterCard(); 
  56.         Thread1 t1 = new Thread1(mc); 
  57.         t1.start(); 
  58.         Thread2 t2 = new Thread2(mc); 
  59.         t2.start(); 
  60.          
  61.     } 
  62.      
  63.     public void charge() 
  64.     { 
  65.         synchronized (this
  66.         { 
  67.             System.out.println("取款1000前:" + money); 
  68.             money -= 1000
  69.             System.out.println("余额:" + money); 
  70.         } 
  71.     } 
  72.      
  73.      
  74.      
  75.     // public void charge() 
  76.     // { 
  77.     // System.out.println("取款前:" + money); 
  78.     // money -= 1000; 
  79.     // System.out.println("余额:" + money); 
  80.     // } 
  81.     // 
  82.      
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI