BlockingQueue 接口源码学习

java version “1.8.0_221”
Java™ SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot™ 64-Bit Server VM (build 25.221-b11, mixed mode)

介绍

BlockingQueue 是一个接口,并且它还继承了 Queue 接口,在继承 Queue 接口的基础上,增加了一些 阻塞式 的操作。

BlockingQueue 中的成员方法有四种形式,分别满足各个场景的需求:

Throws excepiton 抛出异常Special value 返回特定值Blocks 阻塞直到方法执行成功Times out 阻塞执行直到超时时间再放弃
Insert 插入add(e)offer(e)put(e)offer(e, time, unit)
Remove 移除remove()poll()take()poll(time,unit)
Examineelement()peek()
  • element 和 peek 仅在 Queue 接口中定义,他们都是返回表头元素,唯一不同的是当队列为空时,element() 方法会抛出 NoSuchElementException。

  • BlockingQueue 不接受 NULL 元素,否则会抛出 NullPointerException,还有就是 poll 操作失败时,会返回 NULL。

public interface BlockingQueue<E> extends Queue<E> {
	
	/**************** 插入元素 *******************/ 
	/**
	* 添加元素,成功返回 true;若队列容量满,抛出 IllegalStateException 异常。当使用容量受限的队列时,推荐使用 offer(E e)
	*/
	boolean add(E e);
	/**
	* 插入成功返回 true,否则返回 false;这个方法好于 add(),add() 插入失败会抛出异常
	*/
	boolean offer(E e);
	/**
	* 空间足够时直接插入,空间不足时进行等待,直到有空间插入
	*/
	void put(E e) throws InterruptedException;
	/**
	* 带超时时间的插入,true-插入成功,false-直到超时时间过了还没有插入进去
	* 等待期间被 interrupted 时,抛出 InterruptedException 异常
	* 若某些不该添加到这个队列的元素被添加进去时,抛出 IllegalArgumentException 异常
	*/
	boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;

	/**************** 删除元素 *******************/ 
   	/**
	* 删除表头元素,若表头元素还不可用,将等待其可用
	* 等待期间被 interrupted 时,抛出 InterruptedException 异常
	*/ 
	E take() throws InterruptedException;
	/**
	* 带超时时间移除表头元素;若超过时间都没有移除成功,返回 null
	* 等待期间被 interrupted 时,抛出 InterruptedException 异常
	*/
	E poll(long timeout, TimeUnit unit)
        throws InterruptedException;
    /**
    * 移除队列中指定元素(可能存在一个或者多个),若队列发生了更改,返回 true。
    */
	boolean remove(Object o);



	/**************** 其它方法 *******************/ 
	/**
	* 返回队列在没有内存或者资源限制下,可以无阻塞地添加元素的数量,一般为 Integer.MAX_VALUE。
	* 由于同一时刻可能有其它线程也在操作这个队列,所以他的返回值不是一直都是可信地。
	*/
	int remainingCapacity();
	/**
	* 队列包含该元素(一个或多个, equals 比较元素是否相等)返回 true
	*/
	public boolean contains(Object o);
	/**
	* 移动队列元素到集合 c 中,这个操作比重复的 poll + add 更有效率。
	* 但是此过程可能发生异常,并且如果方法执行过程中,c 发生了变化,将会造成不可预知的结果。
	*/
	int drainTo(Collection<? super E> c);
	/**
	* 移动队列中 maxElements 个元素到集合 c 中
	*/
	int drainTo(Collection<? super E> c, int maxElements);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值