Notify和NotifyALL

290 阅读1分钟

面试的时候,面试官让我写一个阻塞队列。其实他的意思就是让我写一个生产者消费者。且不谈Lock等JUC的东西。他实际考察的是sync、notify、notifyall这些东西。

我用了两把锁,一个生产者锁,一个消费者锁。我当时在牛客上写了算是伪代码。

    private ArrayList<Integer> arr = new ArrayList<>();

    private Object p = new Object();
    private Object c = new Object();

    public Integer get() {
        if (arr.size() == 0) {
            try {
                // 生产者阻塞
                p.wait();
                c.notify();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // consumer ...
        return arr.get(0);
    }

    public void put(Integer integer) {
        // 假设 容量为5
        if (arr.size() == 5) {
            try {
                c.wait();
                p.notify();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // produce
    }
  • 其实这个是一个典型的面试题,面试官首先说,if应该换成while,这确实是一个点
  • 他问我为什么有了notify再搞出来一个notifyall?

这其实就是我这片帖子想讨论的重点:有了notify再搞出来一个notifyall?

他跟我说notify会造成死锁,notifyall不会。