栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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实现生产者消费者问题

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号