/**
* 验证同步函数的锁是this对象,static函数锁为类名.class
*/
class TestThreadLock {
public static void main(String[] args) throws InterruptedException {
Custom custom = new Custom();
Thread t1 = new Thread(custom);
Thread t2 = new Thread(custom);
t1.start();
//主线程sleep后,触发t1线程执行
Thread.sleep(10);
//触发t2线程
custom.flag = false;
t2.start();
}
}
class Bank {
int money = 100;
public void outMoney() {
if (money > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "代码:客户正在取钱,钱柜还剩" + (money--) + "元");
}
}
}
class Custom implements Runnable {
Bank bank = new Bank();
boolean flag = true;
@Override
public void run() {
if (flag) {//flag == true 的时候触发代码锁
while(true){
//定义代码锁
synchronized (this) {
bank.outMoney();
}
}
} else {//flag == false 的时候触发函数锁
while(true){
run2();
}
}
}
//定义函数锁
public synchronized void run2() {
if (bank.money > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "函数:客户正在取钱,钱柜还剩" + (bank.money--) + "元");
}
}
}