简介
资源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();
相关文章:
-
2021-04-10
-
2022-12-23
-
2022-01-19
-
2021-07-08
-
2021-09-25
-
2022-01-08
-
2023-03-18