Java 生产者消费者synchronized 中为什么不能是if而要是while

实现示例

仓库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操作, 我们假设如下的步骤发生了:

  1. A 拿到了锁

  2. A 发现size==0, 然后进入等待,并释放锁

  3. 此时B拿到了锁,发现size==0,然后进入等待,并释放锁

  4. 这个时候有个线程C往里面加了个数据1, 那么 notifyAll 所有的等待的线程都被唤醒了.

  5. AB 重新获取锁, 假设 又是A拿到了. 然后 他就移除了一个数据,没有问题.

  6. A 移除数据后 想通知别人, 此时list的大小有了变化, 于是调用了notifyAll , 这个时候就把B给唤醒了, 那么B接着往下走.

  7. 这时候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();
        }
    }

参考:

Java synchronized 中的 while和if

Java实现生产者消费者问题

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值