package com.Java;

//银行不安全案例 两个人同时取钱
//使用 synchronized和synchronized块 可以锁住对象 保证线程的安全性
public class TestBank {
public static void main(String[] args) {

Account account = new Account(50);
Drawing you = new Drawing(account, 50, "你");
Drawing youGirl = new Drawing(account, 50, "你妻子");
new Thread(you).start();

new Thread(youGirl).start();

}
}

class Account {
int money; //手里有多少钱

public Account(int money) {
this.money = money;
}
}

class Drawing extends Thread {

private Account account; //账户
int drawing; //取款多少钱

public Drawing(Account account, int drawing, String name) {
super(name);//把名字传给Thread 这里相当于getName的值
this.account = account;
this.drawing = drawing;
}

@Override
public /*synchronized*/ void run() { //synchronized 指人对象默认是this 即当前所在类的对象
synchronized (account) { //synchronized块可以锁指定对象
if (account.money - drawing < 0) {
System.out.println("钱不够 取不了");
return;
}
System.out.println(this.getName() + "取了" + drawing + "万");
account.money = account.money - drawing;
System.out.println("余额还有" + account.money);
}

}
}