• 阻塞队列


    一、阻塞队列说明

    ArrayBlockingQueue是个底层以数组实现为基础的阻塞队列,由于该阻塞队列的构造函数中都有capacity,所以它是一个有界阻塞队列。

     常用方法和区别如下:

      抛出异常 特殊值 阻塞
    插入
    // 放入元素,如果队列满了,则抛出异常
    public boolean add(E e) {
        return super.add(e);
    }
    public boolean add(E e) {
    if (offer(e))
    return true;
    else
    throw new IllegalStateException("Queue full");
    }

    真正调用的是父类AbstractQueue.add(E e)方法

    public boolean offer(E e) {
      checkNotNull(e);
    final ReentrantLock lock = this.lock; lock.lock(); try { if (count == items.length) return false; else { enqueue(e); return true; } } finally { lock.unlock(); } }
    如果队列满了,返回false 
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    如果队列满了,则阻塞等待

    移除
    public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    如果队列为空,则抛NoSuchElementException();

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

    如果队列为空,返回null

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    如果队列为空,则阻塞等待

    读取
    public E element() {
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    如果对列为空,则抛NoSuchElementException();

    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }

    队列为空,返回null

    不可用 
      上述3个方法在AbstractQueue中 上述3个方法在ArrayBlockingQueue中 底层使用了Condition队列
  • 相关阅读:
    孩子们的游戏(圆圈中最后剩下的数)
    求1+2+3+...+n
    扑克牌顺子
    Java 好文整理
    翻转单词顺序列
    左旋转字符串
    和为S的两个数字
    和为S的连续正数序列
    平衡二叉树
    java 构造函数
  • 原文地址:https://www.cnblogs.com/panning/p/13665835.html
Copyright © 2020-2023  润新知