JAVA队列-接口

前言

说到队列,大家都不陌生,很多场景都需要使用到队列,今天我们一起学习JDK提供的队列源码

类图

在这里插入图片描述
Queue接口的实现类有很多
在这里插入图片描述
从中,我们看到几个熟悉的,BlockingQueue 阻塞队列、Deque 双端队列

Queue

官方介绍:

A collection designed for holding elements prior to processing.
Besides basic {@link java.util.Collection Collection} operations,
queues provide additional insertion, extraction, and inspection
operations. Each of these methods exists in two forms: one throws
an exception if the operation fails, the other returns a special
value (either {@code null} or {@code false}, depending on the
operation). The latter form of the insert operation is designed
specifically for use with capacity-restricted {@code Queue}
implementations; in most implementations, insert operations cannot
fail.

用于在处理前保存元素的集合。除了基本的Collection操作外,队列还提供额外的插入、提取和检查操作。
这些方法都以两种形式存在:
一种在操作失败时抛出异常,另一种返回特殊的值 null 或 false,取决于操作后一种形式的插入操作是专门为有容量限制的{@code Queue} 实现设计的;在大多数实现中,插入操作不会失败

接口方法

  • add() : 添加元素,成功返回true,队列满时抛出异常
  • offer() : 添加元素,队列满时返回false
  • remove() : 从头部删除队列元素并返回该元素,队列空时抛出异常
  • peek() : 返回队列头部元素不删除,队列空时返回null
  • element() : 与peek()方法一样,队列空时抛出异常

BlockingQueue

阻塞队列接口,继承Queue接口
方法特性:
1.抛出异常
2.存储元素
3.阻塞
4.超时

  • 插入元素:
    add(e)、offer(e)、put(e)、offer(e,time,unit)
  • 移除元素:
    remove()、poll()、take()、poll(time,unit)
  • 检出元素:
    element()、peek()

方法列表:

在这里插入图片描述

相比Queue接口,重载了offer和poll 方法,新增加了take、put等方法

接口方法

重点看一下重载的offer和poll方法,及新增的take和put方法

  • boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException;
    往队列添加一个元素,队列满时,阻塞等待timeout时间,成功返回true,失败返回false,不能添加null元素

  • E poll(long timeout, TimeUnit unit) throws InterruptedException;
    检出并删除队列头部元素,队列空时,阻塞等待timeout时间,成功返回头部元素,失败返回null

  • E take() throws InterruptedException;
    检索并删除队列头部元素,队列空时,阻塞等待有元素为止

  • void put(E e) throws InterruptedException;
    添加元素到队列中,队列满时,阻塞等待可用空间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值