//package hl.crja.toob.multhread;
/**
* 同步监视器 : 使用 synchronized 修饰的 对象
* 同步代码块 : 使用 synchronized 修饰的 代码块
* 同步方法 : 使用 synchronized 修饰的 方法
*
* eg :
* synchronized (obj) // obj 为 同步监视器
* {
* ...// 此处为 同步代码块
* }
* public synchronized void test(String aaa) // 此方法为 同步方法
* {
* System.out.println(aaa);
* }
*
* @author Liu Huan
*/
/**
* 账户类:包含 账户id 和 账户余额
*/
public class Account {
private String id;
private int balance;
public Account(String id,int balance){
this.id = id;
this.balance = balance;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
}
/**
* 取钱线程
* acc 接收 传进来的 账户对象的引用
* drawAmount 要取的 钱的总量
*/
class DrawMoney extends Thread {
private Account acc;
private int drawAmount;
// 取钱线程的名字 取钱的账户 取钱的总量
public DrawMoney(String name, Account acc, int drawAmount){
super(name);
this.acc = acc;
this.drawAmount = drawAmount;
}
@Override
public void run() {
//synchronized (acc) { // 是否使用 同步监视器
if (acc.getBalance()>drawAmount){
System.out.println(getName() + "取钱成功" + "金额:" + drawAmount);
acc.setBalance(acc.getBalance()-drawAmount);
System.out.println(getName() + "取后,账户余额:" + acc.getBalance());
} else {
System.out.println(getName() + "取钱失败");
}
//}
}
}
class DrawTest {
public static void main(String[] args) throws InterruptedException {
var acct = new Account("1234",1000);
var p = new DrawMoney("甲", acct, 800);
p.start();
var pp = new DrawMoney("乙", acct, 800);
pp.start();
var ppp = new DrawMoney("丙", acct, 800);
ppp.start();
}
}
不使用 同步代码块,运行结果:
开启同步代码块,结果: