实现示例
仓库Storage.java
import java.util.LinkedList;
/* 仓库 */
public class Storage {
/* 仓库容量 */
private final int MAX_SIZE = 10;
/* 仓库载体 */
private LinkedList<Object> list = new LinkedList<>();
public void produce(){
synchronized (list){
if(list.size() == MAX_SIZE){
System.out.println("[生产者" + Thread.currentThread().getName() + "] 仓库已满");
try{
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(new Object());
System.out.println("[生产者" + Thread.currentThread().getName() + "生产1个产品] 现库存:" + list.size());
list.notifyAll();
}
}
public void consume(){
synchronized (list){
if(list.size() == 0){
System.out.println("[消费者" + Thread.currentThread().getName() + "] 仓库为空");
try{
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove();
System.out.println("[消费者" + Thread.currentThread().getName() + "消费1个产品] 现库存:" + list.size());
list.notifyAll();
}
}
}
生产者:
public class Producer implements Runnable {
/* 生产者 */
private String name;
private Storage storage;
public Producer(Storage storage, String name){
this.storage = storage;
this.name = name;
}
@Override
public void run() {
while (true){
try{
Thread.sleep((long) (5000*Math.random()));
storage.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者:
public class Consumer implements Runnable {
private Storage storage;
private String name;
private Consumer(){}
public Consumer(Storage storage,String name){
this.storage = storage;
this.name = name;
}
@Override
public void run() {
while (true){
synchronized (storage){
try {
Thread.sleep((long) (1000*Math.random()));
storage.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
问题分析
上面的代码运行时会在仓库类consume方法的list.remove报错,那么我们来分析下:
假设现在有A, B两个线程来执行consume操作, 我们假设如下的步骤发生了:
-
A 拿到了锁
-
A 发现size==0, 然后进入等待,并释放锁
-
此时B拿到了锁,发现size==0,然后进入等待,并释放锁
-
这个时候有个线程C往里面加了个数据1, 那么 notifyAll 所有的等待的线程都被唤醒了.
-
AB 重新获取锁, 假设 又是A拿到了. 然后 他就移除了一个数据,没有问题.
-
A 移除数据后 想通知别人, 此时list的大小有了变化, 于是调用了notifyAll , 这个时候就把B给唤醒了, 那么B接着往下走.
-
这时候B就出问题了, 因为 其实 此时的竞态条件已经不满足了 (size==0). B以为还可以删除就尝试去删除, 结果就跑了异常了.
总结
问题的原因就是线程判断条件如果是用if后再wait(),当被notify()之后会继续执行下面的加库和减库操作,而跳过了重新判断条件的步骤,所以判断条件要用while,即将仓库类的produce和consume改为:
public void produce(){
synchronized (list){
//改为while
while(list.size() == MAX_SIZE){
System.out.println("[生产者" + Thread.currentThread().getName() + "] 仓库已满");
try{
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(new Object());
System.out.println("[生产者" + Thread.currentThread().getName() + "生产1个产品] 现库存:" + list.size());
list.notifyAll();
}
}
public void consume(){
synchronized (list){
//改为while
while(list.size() == 0){
System.out.println("[消费者" + Thread.currentThread().getName() + "] 仓库为空");
try{
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove();
System.out.println("[消费者" + Thread.currentThread().getName() + "消费1个产品] 现库存:" + list.size());
list.notifyAll();
}
}