Java 中的 BlockingDeque peek() 方法及示例
在 Java 中,我们可以使用 BlockingDeque 接口来实现双端队列。BlockingDeque 接口继承自 BlockingQueue 接口,提供了在队首和队尾插入或删除元素的方法,并支持阻塞式的操作。其中,peek() 方法用于返回队列的头元素,但并不会将其从队列中删除。
BlockingDeque 的定义和常用方法
public interface BlockingDeque<E> extends BlockingQueue<E>, Deque<E> {
E takeFirst() throws InterruptedException;
E takeLast() throws InterruptedException;
E pollFirst(long timeout, TimeUnit unit) throws InterruptedException;
E pollLast(long timeout, TimeUnit unit) throws InterruptedException;
boolean offerFirst(E e, long timeout, TimeUnit unit)
throws InterruptedException;
boolean offerLast(E e, long timeout, TimeUnit unit)
throws InterruptedException;
void putFirst(E e) throws InterruptedException;
void putLast(E e) throws InterruptedException;
boolean offerFirst(E e);
boolean offerLast(E e);
E takeFirst();
E takeLast();
E pollFirst();
E pollLast();
boolean removeFirstOccurrence(Object o);
boolean removeLastOccurrence(Object o);
boolean add(E e);
boolean offer(E e);
void put(E e) throws InterruptedException;
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
E take() throws InterruptedException;
E poll(long timeout, TimeUnit unit) throws InterruptedException;
int remainingCapacity();
boolean remove(Object o);
boolean contains(Object o);
public int size();
Iterator<E> iterator();
Iterator<E> descendingIterator();
}
从接口定义中可以看出,BlockingDeque 继承自 BlockingQueue 和 Deque 接口,提供了一些插入、删除、获取元素的方法,包括:
- takeFirst()、takeLast():移除并返回队列的头元素或尾元素,如果队列为空则会阻塞等待;
- pollFirst()、pollLast():移除并返回队列的头元素或尾元素,如果队列为空则立即返回 null;
- offerFirst(E e)、offerLast(E e):在队列的头部或尾部插入元素,如果队列已满则返回 false;
- putFirst(E e)、putLast(E e):在队列的头部或尾部插入元素,如果队列已满则会一直阻塞等待;
- offerFirst(E e, long timeout, TimeUnit unit)、offerLast(E e, long timeout, TimeUnit unit):在队列的头部或尾部插入元素,如果队列已满则会等待指定的时间;
- peekFirst()、peekLast():返回队列的头元素或尾元素,但并不会将其从队列中删除。
BlockingDeque peek() 方法的使用示例
下面通过一个示例代码来说明 BlockingDeque peek() 方法的使用。
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
public class BlockingDequeDemo {
public static void main(String[] args) throws InterruptedException {
BlockingDeque<Integer> deque = new LinkedBlockingDeque<>(2);
deque.add(1);
deque.add(2);
Integer head = deque.peek();
System.out.println("队列头元素:" + head); // 输出:队列头元素:1
deque.remove();
Integer newHead = deque.peek();
System.out.println("移除头元素后的队列头元素:" + newHead); // 输出:移除头元素后的队列头元素:2
Integer nullHead = deque.peek();
System.out.println("队列为空时返回值:" + nullHead); // 输出:队列为空时返回值:null
}
}
在上面的示例代码中,我们首先创建了一个容量为 2 的双端队列,然后向队列中添加了两个元素。接着,我们使用 peek() 方法获取队列的头元素,可以发现它返回的是 1。然后,我们移除掉队列头部的元素,并再次使用 peek() 方法获取队列头部的元素,发现返回的是 2。最后,我们移除了队列头部以外的所有元素,并使用 peek() 方法获取队列头部元素,此时由于队列为空,因此 peek() 方法返回 null。
结论
BlockingDeque 接口提供了一个 peek() 方法,用于返回队列头部或尾部的元素,并不会将其从队列中删除。在使用时需要注意队列是否为空的情况,如果队列为空,则 peek() 方法返回 null。