1 Queue接口的基本认识
(1) Queue接口的结构
所有的父接口:
Collection<E>, Iterable<E>
所有的子接口:
BlockingDeque<E>, BlockingQueue<E>, Deque<E>, TransferQueue<E>
所有的实现类:
AbstractQueue
, ArrayBlockingQueue
, ArrayDeque
, ConcurrentLinkedDeque
, ConcurrentLinkedQueue
, DelayQueue
, LinkedBlockingDeque
, LinkedBlockingQueue
, LinkedList
, LinkedTransferQueue
, PriorityBlockingQueue
, PriorityQueue
, SynchronousQueue
(2) 方法
除了基本的集合Collection操作,队列还提供了其他的插入、提取和检查操作,总结如下:
方法名称 | 描述 |
---|---|
add(E e) | 往队列尾部中插入新的元素,如果成功,返回true;如果空间不足,返IllegalStateException |
element() | 取队列头部的数据,但是不删除 |
offer(E e) | 添加一个元素并返回true,如果队列已满,则返回false。不会报错,直接返回false |
peek() | 取队列头部的数据,但是不删除。如果队列为空,返回null |
poll() | 取队列头部的数据,并且删除。如果队列为空,则返回null |
remove() | 取队列头部的数据,并且删除。如果队列为空,则报错 |
2 Queue接口实现类
Java中实现Queue接口的类,分为两类,一类是非阻塞队列,另一类是阻塞队列。
当队列中没有数据的情况下,如果有线程想要从该队列中读取数据时,这个线程就会被阻塞进入等待状态,直到其他线程在该队列中插入元素,被阻塞的线程才会被唤醒。同样,如果队列以满,视图往队列中存放元素的线程也会被阻塞进入等待状态,直到该队列中的元素被其他线程拿走,被阻塞的线程才会被唤醒。阻塞队列用队列+Lock
来实现的。
(1) 非阻塞队列
- LinkedList
- PriorityQueue
- ConcurrentLinkedQueue
(2) 阻塞队列 - ArrayBlockingQueue
- LinkedBlockingQueue
- PriorityBlockingQueue
- DelayQueue
- SynchronousQueue
(3) 使用java的队列
public class TestQueue {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < 10; i++) {
queue.add(i);
}
Integer top = queue.remove();
System.out.println("队列头部的元素:" + top);
int size = queue.size();
System.out.println("队列的大小:" + size);
}
}
参考:
[1] https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
[2] https://www.cnblogs.com/yuansc/p/9087044.html
[3] 深入了解JAVA 阻塞队列原理到底能给我们带来什么帮助 - 追逐的文章 - 知乎
https://zhuanlan.zhihu.com/p/90867663