4

我编写了解决有界生产者和消费者问题的程序。在构建时ArrayBlockingQueue,我定义了容量 100。我正在使用方法 take 和 put 内部线程。而且我注意到,有时我会看到 102 次 put ,它们之间有任何 take 。为什么会这样?

生产者运行方法:

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
4

1 回答 1

5

我定义了容量 100。我正在使用方法 take 和 put 内部线程。而且我注意到,有时我会看到 102 次 put ,它们之间有任何 take 。为什么会这样?

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

如果有任何问题,打印出来queue.size()看看它是否超过 100。ArrayBlockingQueue永远不会告诉你。

于 2012-10-23T22:51:33.553 回答