Java中BlockingQueue的poll()方法及示例
前言
在多线程编程中,经常需要使用到阻塞队列,因为它是一种线程安全的数据结构。在Java中,BlockingQueue是一个接口,它继承自Queue接口,提供了阻塞操作的队列方法。
BlockingQueue有很多实现类,如ArrayBlockingQueue、LinkedBlockingQueue等。其中,poll()是BlockingQueue中的一个方法,用于取出队列中的元素。
BlockingQueue的poll()方法
poll()方法用于取出队列中的元素,如果队列为空,则返回null。如果队列非空,则返回队列头的元素。调用该方法会移除掉队列头的元素,故而其返回值可以用来判断poll()方法是否调用成功。
poll()方法有两种形式:poll()和poll(long timeout, TimeUnit unit)。第一个形式的poll()方法是一个非阻塞方法,如果队列为空,它将立即返回null。第二个形式的poll(long timeout, TimeUnit unit)方法会等待队列中有元素出现,等待时间结束后,如果队列为空,则返回null,否则返回队列头的元素。
E poll()
方法如下所示:
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 获取并删除此队列的头部,在此队列为空时返回 null。
Integer element = queue.poll();
E poll(long timeout, TimeUnit unit)
方法如下所示:
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 获取并删除此队列的头部,在指定的等待时间内有效,则返回 null。
Integer element = queue.poll(1, TimeUnit.SECONDS);
示例
下面是一个使用BlockingQueue的简单示例,包含了poll()方法的使用:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
// 插入两个元素到队列中
queue.put(1);
queue.put(2);
// 使用poll()方法取出队列中的元素
System.out.println(queue.poll()); // 输出1
System.out.println(queue.poll()); // 输出2
// 队列已空,再次取出元素返回null
System.out.println(queue.poll()); // 输出null
// 使用poll(long timeout, TimeUnit unit)方法取出队列中的元素
new Thread(() -> {
try {
// 线程等待3秒后,取出队列中的元素
System.out.println(queue.poll(3, java.util.concurrent.TimeUnit.SECONDS)); // 输出3
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
// 队列中插入一个元素
queue.put(3);
// 阻塞1秒钟,等待另一个线程取出队列中的元素
Thread.sleep(1000);
// 队列已空,再次取出元素返回null
System.out.println(queue.poll()); // 输出null
}
}
结论
在使用阻塞队列时,我们可以通过poll()方法来取出队列中的元素,该方法有两种形式,根据需要进行选择即可。需要注意的是,队列为空时,poll()方法会立即返回null,因此需要考虑队列为空的情况,避免出现空指针异常等问题。