/**
*同步代码块:synchronized (Obj){执行体…}
?*
* Obj称之为同步监视器,可以是任何对象,但是推荐使用共享资源作为同步监视器。
*不同方法中无需指定同步监视器,因为同步方法中的同步监视器就是this,就是这个对象本身,或者是class。
?*/
public class MyBank2{
????public static void main(String[] args) throws InterruptedException {
Account2 account = new Account2(1000, "旅游基金");
new Bank2(account, 500, "你").start();
new Bank2(account, 600, "女朋友").start();
????}
}
//账户
class Account2 {
//账户总余额
????int money;
//账户名
????String name;
????public Account2(int money, String name) {
????????this.money = money;
????????this.name = name;
????}
}
//银行
class Bank2 extends Thread{
//客户账户
????Account2 account;
//取得钱数
????int drawingMoney;
????public Bank2(Account2 account, int drawingMoney, String name) {
????????super(name);
????????this.account = account;
????????this.drawingMoney = drawingMoney;
????}
????@Override
????public void run() {
????????synchronized (account) {
????????????if (account.money- drawingMoney < 0) {
System.out.println(account.name+ "钱不够了,取不了了");
????????????????return;
????????????}
????????????try {
????????????????Thread.sleep(500);
????????????} catch (InterruptedException e) {
????????????????e.printStackTrace();
????????????}
//卡内余额 = 余额 - 取得钱
????????????account.money = account.money - drawingMoney;
System.out.println(Thread.currentThread().getName() ?+ "取了" + drawingMoney);
System.out.println(account.name + "余额为:" + account.money);
????????}
????}
}