ArrayBlockingQueue超出给定容量

时间:2012-10-23 22:49:11

标签: java concurrency java.util.concurrent capacity

我写过程序解决有限生产者&消费者问题。构建ArrayBlockingQueue时,我定义了容量100.我正在使用方法接受并放入线程。而且我注意到有时候我会看到102次与他们之间的任何拍摄。为什么会这样?

生产者运行方法:

public void run() {
    Object e = new Object();
    while(true) {
        try {
            queue.put(e);
        } catch (InterruptedException w) {
                System.out.println("Oj, nie wyszlo, nie bij");
        }
        System.out.println("Element added");

    }
}

消费者运行方法:

public void run() {
    while(true) {
        try {
            queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Element removed");
    }
}

带输出的文件uniq -c的一部分:

102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
102 Element removed
102 Element added
  2 Element removed
  2 Element added
102 Element removed
102 Element added

1 个答案:

答案 0 :(得分:5)

  

我定义了容量100.我正在使用方法接受并放入线程。而且我注意到有时候我会看到102次与他们之间的任何拍摄。为什么会这样?

这很可能是输出中竞争条件的副产品,而不是暗示阻塞队列在队列中有超过100个条目。在将元素放入队列之后,线程可能会从队列中删除某些内容,但在之前显示"removed"消息,推杆可以显示"added"消息 - 反之亦然。队列调用与System.out.println(...)之间没有锁定,因此无法保证顺序。

如果有任何问题,请打印queue.size()以查看它是否超过100. ArrayBlockingQueue绝不会向您显示。