wait() notify常用来程序在不满足某个条件时挂起,满足后再唤醒的应用场景。
而虚假唤醒的问题是:某个程序越过判断条件非法执行产生预料之外的执行结果。
我们来看一个买卖商品的场景:
package com.songtao.concurrencycoding.wait;
public class WaitDemo {
/**
* 商品资源类
*/
static class ItemResource{
private int num;
private static final int MAX = 10;
/**
* 添加商品
* */
public synchronized void put() throws InterruptedException {
if(num >= MAX){
// while (num >= MAX){
//doSomething
System.out.println("商品到达最大库存");
this.wait();//挂起
}
num++;
System.out.println(Thread.currentThread().getName()+"当前商品剩余"+num);
this.notifyAll();
}
/**
* 售卖商品
* */
public synchronized void sell() throws InterruptedException {
if(num <= 0){
// while (num <= 0){
//doSomething
System.out.println("商品已经全部售出,等待商品添加");
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"当前商品剩余"+num);
this.notifyAll();
}
}
public static void main(String[] args){
ItemResource items = new ItemResource();
new Thread(()->{
for(int i=0;i<20;i++){
try {
Thread.sleep(100);
items.put();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A生产者").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
Thread.sleep(100);
items.sell();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B1消费者").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
Thread.sleep(100);
items.sell();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B2消费者").start();
}
}
执行结果:
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
A生产者当前商品剩余1
B1消费者当前商品剩余0
B2消费者当前商品剩余-1
商品已经全部售出,等待商品添加
A生产者当前商品剩余0
B2消费者当前商品剩余-1
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
A生产者当前商品剩余0
B2消费者当前商品剩余-1
B1消费者当前商品剩余-2
A生产者当前商品剩余-1
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
A生产者当前商品剩余0
B1消费者当前商品剩余-1
B2消费者当前商品剩余-2
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
A生产者当前商品剩余-1
B2消费者当前商品剩余-2
B1消费者当前商品剩余-3
商品已经全部售出,等待商品添加
A生产者当前商品剩余-2
B1消费者当前商品剩余-3
商品已经全部售出,等待商品添加
A生产者当前商品剩余-2
B2消费者当前商品剩余-3
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
A生产者当前商品剩余-2
B2消费者当前商品剩余-3
B1消费者当前商品剩余-4
A生产者当前商品剩余-3
商品已经全部售出,等待商品添加
商品已经全部售出,等待商品添加
在这个场景中,当我们执行多个消费者的时候就会产生虚假唤醒的问题,这是因为当生产者生产出商品后会唤醒所有等待中的线程,但因为之前被挂起的程序在挂起之后被唤醒时并不会对商品数量进行判断@code if(num <= 0),从而使另一个线程消费后明明商品数量已经为0,但被唤醒的线程从原地“复活”,接着消费。
解决方法:唤醒的线程需要对商品数量再次判断,校验执行的合法性。只需把if判断用循环判断代替即可。if(num >= 0) ->while(num >= 0)
结论:wait必须放在条件判断循环之中来防止虚假唤醒的问题。
运行结果: