从头开始实现BlockingQueue的问题

时间:2016-11-10 19:13:48

标签: java multithreading synchronization blockingqueue

我正在尝试基于一个found here构建我自己的BlockingQueue变体。

    Thread thread1 = new Thread() {
        public void run() {
            queue.add(1);
            queue.add(2);
        }
    };

    Thread thread2 = new Thread() {
        public void run() {
            System.out.println(queue.remove());
            System.out.println(queue.remove());
        }
    };      

但是出于某种原因,当我尝试运行这样的线程时

spark-submit

我得到了这个例外

  

线程“Thread-3”中的异常java.lang.NullPointerException       在ThreadSafeContainer.remove(ThreadSafeContainer.java:52)       在ThreadPractice $ 2.run(ThreadPractice.java:17)       在java.lang.Thread.run(未知来源)

我可以通过将size == 0更改为front == null来删除错误,但它仍然不会输出相同的内容。

1 个答案:

答案 0 :(得分:0)

目前,如果对remove()的调用删除了最后一个元素,则最终会使用front == nullend == //the last created node。这意味着,对add的下一次调用只会更新end,而不是front,而对remove()的相应调用会抛出您的NPE。

您可以在front == null末尾检查remove(),或将add中的测试从end == null更改为size == 0或{{1} }。

顺便说一句,如果你发布了一个堆栈跟踪,那么添加一条注释会有助于你的代码段中哪一行与异常中的行号相对应。