gpt4 book ai didi

java - 如何创建容量受限的队列实现?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:47 25 4
gpt4 key购买 nike

在Java API文档中,我试图从实现的角度来理解下面的解释。

http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html

Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.

所以,我想写一个程序来验证一下,在什么情况下会抛出异常。如何创建容量受限的队列实现和验证?

有人可以举例说明吗?

最佳答案

你应该使用 BlockingQueue例如ArrayBlockingQueue ,即:

A bounded blocking queue backed by an array. 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.

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.

关于java - 如何创建容量受限的队列实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com