java队列如何使用
队列的基本概念
队列是一种先进先出(FIFO)的数据结构,支持在队尾添加元素(入队),在队头移除元素(出队)。Java中队列的实现主要通过java.util.Queue接口及其实现类(如LinkedList、ArrayDeque、PriorityQueue等)。
队列的常用方法
-
入队操作
add(E e):将元素插入队尾,若队列已满抛出异常。offer(E e):将元素插入队尾,返回是否成功(推荐使用)。Queue<Integer> queue = new LinkedList<>(); queue.offer(1); // 推荐 queue.add(2); // 可能抛出异常
-
出队操作
remove():移除队头元素并返回,若队列为空抛出异常。poll():移除队头元素并返回,队列为空时返回null(推荐使用)。Integer head = queue.poll(); // 推荐 Integer head2 = queue.remove(); // 可能抛出异常
-
查看队头元素
element():返回队头元素但不移除,若队列为空抛出异常。peek():返回队头元素但不移除,队列为空时返回null(推荐使用)。Integer first = queue.peek(); // 推荐
队列的实现类
-
LinkedList
双向链表实现,支持队列和双端队列操作。Queue<String> queue = new LinkedList<>(); queue.offer("A"); queue.offer("B"); -
ArrayDeque
基于数组的双端队列,性能优于LinkedList,但容量固定。Queue<Integer> queue = new ArrayDeque<>(10); queue.offer(10); -
PriorityQueue
优先级队列,元素按自然顺序或自定义Comparator排序。Queue<Integer> pq = new PriorityQueue<>(); pq.offer(3); pq.offer(1); // 出队顺序为1, 3
阻塞队列(高级场景)
BlockingQueue接口(如ArrayBlockingQueue、LinkedBlockingQueue)支持线程安全的阻塞操作:
put(E e):队列满时阻塞等待。take():队列空时阻塞等待。BlockingQueue<Integer> bq = new ArrayBlockingQueue<>(5); bq.put(1); // 阻塞直到有空位 int val = bq.take(); // 阻塞直到有元素
注意事项
- 优先使用
offer/poll/peek避免异常。 - 多线程环境选择
ConcurrentLinkedQueue或BlockingQueue实现。 PriorityQueue的排序需确保元素实现Comparable或提供Comparator。
通过合理选择实现类和操作方法,可以高效处理任务调度、消息传递等场景。







