package com.jirong.syn;
//不安全的银行问题
//两人去银行取钱
//需要有银行对象,取钱的账号对象
public abstract class BankTest {
public static void main(String[] args) {
// 账户对象
Account account = new Account(100, "读书费用");
// 银行对象(取钱对象)
Drawing you = new Drawing(account, 50, "you");
Drawing girlFriend= new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.start();
}
}
//账号
class Account {
int money;//余额
String name;//账号名字
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行;模拟取款
class Drawing extends Thread {
final Account account;//账号
// 取走的钱
int drawingMoney;
// 手里的钱
int nowMoney;
// 取款人的姓名,线程操作对象,取款人
public Drawing(Account account, int drawingMoney, String name) {
super(name);
// this.name = name;
this.account = account;
this.drawingMoney = drawingMoney;
}
// 取钱
//synchronized
@Override
public void run() {
// 银行一直在哪,但不一定是一个银行取钱,但账号是固定,2个人公用的,故锁账号
// 锁的是执行操作的公共资源,共用了一个账号,操作全在账号这
synchronized (account){
// 判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够了,取不出来");
return;
}
// 线程休眠下,模拟取钱花时间,放大问题的发现行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 卡内余额
account.money = account.money - drawingMoney;
// 手上的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额" + account.money);
// 该线程开启人手里的钱,继承了Thread
// this.getName()=Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
}