阻塞队列的通用操作

阻塞队列都是实现BlockingQueue接口的,因此他们方法都是一样的

API和不可用的处理方式

当阻塞队列不可用时(向满的队列插入,从空队列取数据),提供了四种处理方式

方法 抛出异常 返回特殊值 一直阻塞 超时退出
插入 boolean add(E e) boolean offer(E e) void put(E e) throws InterruptedException boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
移除 void remove() poll() E take() throws InterruptedException E poll(long timeout, TimeUnit unit) throws InterruptedException
查看 element() peek() 不可用 不可用

抛出异常

  • 满了继续插入会抛出:IllegalStateException ("Queue full")
  • 空了继续出队会抛出:NoSuchElementException

返回特殊值

  • 满了继续插入会返回false
  • 空了继续出队会返回null

一直阻塞

  • 满了继续插入会阻塞,直到有空位或被中断
  • 空了继续出队会阻塞,直到有元素或被中断

超时退出

也是会阻塞,但是达到一定时间还没成功就返回特殊值了

results matching ""

    No results matching ""