美文网首页
生产者消费者问题中的临界判断为什么要用while

生产者消费者问题中的临界判断为什么要用while

作者: Mr_Editor | 来源:发表于2020-06-18 18:04 被阅读0次
  • 问题背景

面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法,能够支持2个生产者线程以及10个消费者线程的阻塞调用

public class MyContainer1<T> {
    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10; //最多10个元素
    private int count = 0;

    public synchronized void put(T t) {
        while(lists.size() == MAX) {                    //想想为什么用while而不是用if?   
            try {
                this.wait(); //effective java
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        lists.add(t);
        ++count;
        this.notifyAll(); //通知消费者线程进行消费
    }
    
    public synchronized T get() {
        T t = null;
        while(lists.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = lists.removeFirst();
        count --;
        this.notifyAll(); //通知生产者进行生产
        return t;
    }
    
    public static void main(String[] args) {
        MyContainer1<String> c = new MyContainer1<>();
        //启动消费者线程
        for(int i=0; i<10; i++) {
            new Thread(()->{
                for(int j=0; j<5; j++) System.out.println(c.get());
            }, "c" + i).start();
        }
        
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        //启动生产者线程
        for(int i=0; i<2; i++) {
            new Thread(()->{
                for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
            }, "p" + i).start();
        }
    }
}

  • 问题分析

在put()方法中,临界判断使用while循环,为什么不能使用if判断呢?

  1. 首先需要注意,在循环判断中调用了this.wait()方法,wait()方法会释放锁,进入阻塞状态;
  2. 在程序中存在两个生产者P0,P1,考虑如下情况:

2.1 P0获得锁,进行临界判断,list满,执行this.wait()方法,进入阻塞状态,P1获得锁,进行临界判断,list满,执行this.wait()方法,释放锁,进入阻塞状态。
2.2 消费者消费元素后调用notifyAll()方法,P0,P1被唤醒,此时P0获得锁, 如果使用的判断是if判断,则会执行add(),执行后list满,释放锁,P1获得锁,从this.wait()后代码开始执行,执行add()方法,list又添加一个元素,超出了最大容量,因此需要使用while循环进行临界条件判断。

相关文章

网友评论

      本文标题:生产者消费者问题中的临界判断为什么要用while

      本文链接:https://www.haomeiwen.com/subject/hazuxktx.html