BlockingQueue
接口是 Java 集合框架 的一部分,它扩展了 Queue
接口。它允许任何操作等待直到成功执行。
例如,如果我们想从一个空队列中删除一个元素,那么阻塞队列允许删除操作等待,直到队列中有可删除的元素为止。
实现 BlockingQueue 的类
由于 BlockingQueue
是一个接口,我们不能直接实现它。
为了使用 BlockingQueue
的功能,我们需要使用实现它的类。

如何使用阻塞队列?
为了使用 BlockingQueue
,我们必须导入 java.util.concurrent.BlockingQueue
包。
// Array implementation of BlockingQueue
BlockingQueue<String> animal1 = new ArraryBlockingQueue<>();
// LinkedList implementation of BlockingQueue
BlockingQueue<String> animal2 = new LinkedBlockingQueue<>();
在这里,我们分别创建了 ArrayBlockingQueue
和 LinkedBlockingQueue
类的对象 animal1 和 animal2。这些对象可以使用 BlockingQueue
接口的功能。
BlockingQueue 的方法
根据队列是满还是空,阻塞队列的方法可以分为 3 类
抛出异常的方法
add()
- 将一个元素插入到阻塞队列的末尾。如果队列已满,则抛出 异常。element()
- 返回阻塞队列的头部。如果队列为空,则抛出异常。remove()
- 从阻塞队列中移除一个元素。如果队列为空,则抛出异常。
返回某些值的方法
offer()
- 将指定元素插入到阻塞队列的末尾。如果队列已满,则返回false
。peek()
- 返回阻塞队列的头部。如果队列为空,则返回null
。poll()
- 从阻塞队列中移除一个元素。如果队列为空,则返回null
。
关于 offer() 和 poll() 的更多信息
offer()
和 poll()
方法可以与超时一起使用。也就是说,我们可以将时间单位作为参数传递。例如,
offer(value, 100, milliseconds)
这里,
- value 是要插入队列的元素
- 我们将超时时间设置为 100 毫秒
这意味着 offer()
方法将尝试将元素插入阻塞队列 100
毫秒。如果在 100 毫秒内无法插入该元素,则该方法返回 false
。
注意:除了 milliseconds
,我们还可以在 offer()
和 poll()
方法中使用以下时间单位:days
、hours
、minutes
、seconds
、microseconds
和 nanoseconds
。
阻塞操作的方法
BlockingQueue
还提供了阻塞操作并等待队列满或空的方法。
put()
- 将一个元素插入到阻塞队列。如果队列已满,它将等待直到队列中有空间可以插入元素。take()
- 从阻塞队列中移除并返回一个元素。如果队列为空,它将等待直到队列中有可删除的元素。
假设我们要向队列中插入元素。如果队列已满,则 put()
方法将等待直到队列中有空间插入元素。
同样,如果我们想从队列中删除元素。如果队列为空,则 take()
方法将等待直到队列包含可删除的元素。
ArrayBlockingQueue 中 BlockingQueue 的实现
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
class Main {
public static void main(String[] args) {
// Create a blocking queue using the ArrayBlockingQueue
BlockingQueue<Integer> numbers = new ArrayBlockingQueue<>(5);
try {
// Insert element to blocking queue
numbers.put(2);
numbers.put(1);
numbers.put(3);
System.out.println("BLockingQueue: " + numbers);
// Remove Elements from blocking queue
int removedNumber = numbers.take();
System.out.println("Removed Number: " + removedNumber);
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
BlockingQueue: [2, 1, 3] Removed Element: 2
要了解更多关于 ArrayBlockingQueue
的信息,请访问 Java ArrayBlockingQueue。
为什么使用 BlockingQueue?
在 Java 中,BlockingQueue
被认为是 **线程安全** 的集合。因为它有助于多线程操作。
假设一个线程正在向队列中插入元素,而另一个线程正在从队列中移除元素。
现在,如果第一个线程运行速度较慢,那么阻塞队列可以让第二个线程等待,直到第一个线程完成其操作。