*同步代码块: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) {
return;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 取得钱
account.money = account.money - drawingMoney;
}
}
}
领取专属 10元无门槛券
私享最新 技术干货