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

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

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

仓库Storage.java

import java.util.linkedList;


public class Storage {


    
    private final int MAX_SIZE = 10;
    
    private linkedList 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();
        }
    }
参考:

Java synchronized 中的 while和if

Java实现生产者消费者问题

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5708260.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)