日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

线程:synchronized方法

發布時間:2025/3/17 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程:synchronized方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

  • 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);?
  • ????//?}?
  • ????//?
  • ?????
  • }?
  • 轉載于:https://blog.51cto.com/glblong/1194998

    總結

    以上是生活随笔為你收集整理的线程:synchronized方法的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。