使用同步块模拟同时取钱

 1 /**
 2  *     使用同步块模拟同时取钱
 3  *
 4  */
 5 public class SynMoney {
 6     public static void main(String[] args) {
 7         CountMoney countMoney = new CountMoney(1000);
 8         Peoples man = new Peoples(90, countMoney);
 9         Peoples woMan = new Peoples(80, countMoney);
10         new Thread(man).start();
11         new Thread(woMan).start();
12     }
13 }
14 
15 //账户金额
16 class CountMoney {
17     public int money;
18     public CountMoney(int money) {
19         this.money = money;
20     }
21 }
22 //取钱的人
23 class Peoples implements Runnable{
24     private int payMoney;
25     private CountMoney countMoney;
26     
27     public Peoples(int payMoney, CountMoney countMoney) {
28         this.payMoney = payMoney;
29         this.countMoney = countMoney;
30     }
31 
32     @Override
33     public void run() {
34         test();
35     }
36     public void test() {
37         synchronized(countMoney) {    //同步块
38             if(countMoney.money-payMoney<0){
39                 return;
40             }
41             System.out.println("账户余额-->"+countMoney.money);
42             countMoney.money -= payMoney;
43             System.out.println("支取-->"+payMoney);
44             System.out.println("账户剩余-->"+countMoney.money);
45         }
46     }
47     
48 }

结果:

  账户余额-->1000
  支取-->90
  账户剩余-->910
  账户余额-->910
  支取-->80
  账户剩余-->830

posted @ 2020-07-09 13:13  梅竹疯狂打豆豆  阅读(194)  评论(0)    收藏  举报