温馨提示×

温馨提示×

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

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

线程:synchronized方法

发布时间:2020-06-30 23:03:15 阅读:582 作者:glblong 栏目:开发技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>
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);     // }     //      } 

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

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

AI

开发者交流群×