为什么 ArrayBlockingQueue 必须有绑定,而 LinkedBlockingQueue 没有?

Why ArrayBlockingQueue must have bound, while LinkedBlockingQueue not?

当我实例化ArrayBlockingQueue时,我还必须在其构造函数中放入int capacity。同样的事情不适用于 LinkedBlockingQueue。我很想知道这是为什么?

当然我也可以把bound放在LinkedBlockingQueue里,但这样是最优的。为什么它在这里是最佳的,而不是 ArrayBlockingQueueArrayBlockingQueue 不能像 ArrayList 那样拥有默认的初始容量吗?

ArrayBlockingQueue 的文档说。

This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

由于容量是固定的且无法更改,因此由 class 的用户决定队列何时开始阻塞。

LinkedBlockQueue 的文档说

An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.

The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.

在这种情况下,根据提供的容量进行阻止。如果指定,则强制执行与 ArrayBlockingQueue

相同的阻塞容量