不安全线程取钱

 1 package 多线程练习;
 2 
 3 import com.sun.javafx.sg.prism.web.NGWebView;
 4 
 5 import java.math.BigDecimal;
 6 
 7 /*
 8    模拟两个人同时取钱的情况
 9  */
10 public class UnSafeAccount {
11     public static void main(String[] args) {
12         Bank bank = new Bank("12345", new BigDecimal("100"));
13         WithDrawMoney xiaoming = new WithDrawMoney(bank, new BigDecimal("50"), "小明");
14         WithDrawMoney xiaomingxf = new WithDrawMoney(bank, new BigDecimal("100"), "小明媳妇");
15         xiaoming.start();
16         xiaomingxf.start();
17 
18     }
19 }
20 
21 
22 /*
23    银行类
24  */
25 class Bank {
26     String cardNumer;    // 卡号
27     BigDecimal balance;  // 余额  小tip:Java中用BigDecimal 来表示金钱类型
28 
29     public Bank(String cardNumer, BigDecimal balance) {
30         this.cardNumer = cardNumer;
31         this.balance = balance;
32     }
33 
34 }
35 
36 class WithDrawMoney extends Thread {
37     //  模拟正式环境全部私有
38     Bank bank;
39     BigDecimal nowMoney = new BigDecimal("0");   // 手里的钱
40     BigDecimal drawMoney;  // 取走的钱
41 
42     // 构造方法
43     public WithDrawMoney(Bank bank, BigDecimal drawMoney, String name) {
44         super(name);  // 调用父类的只能用在第一行
45         this.bank = bank;
46         this.drawMoney = drawMoney;
47     }
48 
49     @Override
50     public void run() {
51         if (bank.balance.subtract(drawMoney).compareTo(BigDecimal.ZERO) == -1) {
52             System.out.println(this.getName() + " 钱不够了,取钱失败");  // 线程类中this.getName() ==  Thread.currentThread.getName()
53             return;
54         }
55 
56         try {
57             Thread.sleep(500);
58         } catch (InterruptedException e) {
59             e.printStackTrace();
60         }
61 
62         nowMoney = nowMoney.add(drawMoney);                       // 手里的钱
63         bank.balance = (bank.balance.subtract(drawMoney));        // 卡上余额 subtract 减法  add 加法
64         System.out.println(this.getName() + " 手里有 " + nowMoney + "钱");
65         System.out.println("卡上余额:" + bank.balance);
66     }
67 
68 
69 }

 

 

输出结果

 

posted @ 2022-01-15 19:48  Chris丶Woo  阅读(33)  评论(0编辑  收藏  举报