虚假唤醒

简介

资源num==0:此时两个消费者线程都wait。

生产者执行num++后,唤醒了所有等待的线程。

此时这两个消费者线程抢占资源后立马执行wait之后的操作,即num--,就会出现产品为负的情况。

为了避免这种情况我们应该让wait()在while()循环中多次判断。

示例

反例:
		if(num<=0) {
			System.out.println("库存已空,无法卖货");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName()+" : "+(num--));
		this.notifyAll();


正例:
		while(num<=0) {
			System.out.println("库存已空,无法卖货");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName()+" : "+(num--));
		this.notifyAll();
原文地址:https://www.cnblogs.com/loveer/p/11518462.html