一、为啥需要等待 - 通知机制
假设线程没拿到锁,一直循环尝试去获取锁,这样效率是很低的,如果有通知机制,那么得到通知了,再执行即可。
二、何为等待 - 通知
如现实中,医院就医顺序:
1、患者挂号,等待叫号。 (等锁)
2、患者被叫号,医生诊治。 (拿到锁)
3、医生问诊,开检查单。(线程缺少执行条件,释放锁)
4、患者检查完,重新等待叫号。(重新尝试拿锁)
5、患者被叫好,医生诊治。(拿锁-执行)
三、如何实现等待 - 通知?
synchronized 配合wait(),notify(),notifyAll()来实现。
wait():当一个线程拿到锁,进入临界区后,由于条件不满足,进入阻塞状态,然后进入等待队列中,线程在进入等待队列的同时,会释放自己所持有的锁。
notify():条件满足了,随机通知等待队列中的一个线程,风险是可能会导致有的线程永远也通知不到。
notifyAll():条件满足了,通知等待队列中的所有线程。
转账代码如何优雅的实现等待/通知?
管理员代码:
package exercise_02_0707;
import java.util.ArrayList;
import java.util.List;
// 单例模式
public class Allocator {
private volatile static Allocator allocator = null; //volatitle 解决指令重排序的问题
private static List lockList = new ArrayList<>();
private Allocator() {
} // 构造方法私有
public static Allocator getAllocator() { //synchronized 保证线程安全
if (allocator == null) {
// 保证所有线程都可以进入,不会因为锁方法而把类锁上,也可以过滤很多,提高性能
synchronized (Allocator.class) { //开始锁住
if (allocator == null) { //防止两个线程同城到达if,又出现线程不安全的问题,双重检查锁
allocator = new Allocator();
}
}
}
return allocator;
}
// 拿到资源
public synchronized void getLock(Object a, Object b) throws InterruptedException {
// while循环,notifyAll通知了之后,需要不断遍历等待队列中有哪些条件是满足了的
while (lockList.contains(a) || lockList.contains(b)) {
wait();
}
lockList.add(a); System.out.println(Thread.currentThread().getName() + " wait");
lockList.add(b);
}
// 释放资源
public synchronized void removeLock(Object a, Object b) {
lockList.remove(a);
lockList.remove(b);
notifyAll();
System.out.println(Thread.currentThread().getName() + " notifyAll");
}
}
账户代码及测试:
package exercise_02_0707;
public class AccountNew {
private Integer balance = 10000; // 账户余额
// 转账操作
void transfer(AccountNew account2, int amt) throws InterruptedException {
Allocator.getAllocator().getLock(this, account2);
synchronized (this) {
synchronized (account2) {
account2.balance += amt;
this.balance -= amt;
}
}
System.out.println(Thread.currentThread().getName() + " over");
Allocator.getAllocator().removeLock(this, account2);
}
public static void main(String[] args) {
AccountNew account = new AccountNew();
AccountNew account2 = new AccountNew();
Thread a = new Thread(()->{
try {
account.transfer(account2,100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread b = new Thread(()->{
try {
account2.transfer(account,90);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread c = new Thread(()->{
try {
account.transfer(account2,90);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
a.start();
b.start();
c.start();
}
}
执行结果:
四、wait和sleep的区别
1、sleep方法属于Thread类,wait方法则属于Object类;
2、sleep不会释放锁,但是wait会;
3、sleep方法必须指定时间;
4、sleep随时可以用,wait用在同步方法和同步块中;
5、sleep方法暂停执行指定的时间,让出cpu给其他线程,但是监控状态依然保持,等到时间到了就会自动恢复运行状态。