zoukankan      html  css  js  c++  java
  • 阻塞队列

    一、阻塞队列说明

    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队列
  • 相关阅读:
    Inner Classes with TypeScript
    设计模式(一)
    C++定义构造函数必须使用初始化列表的场合
    制作Linux下程序安装包——使用脚本打包bin、run等安装包
    Windows下将程序打包为安装包(最为简易的方式)
    在Linux中查看文件的编码及对文件进行编码转换
    libpcap文件格式分析
    static_cast, dynamic_cast, const_cast
    字符1与数字1
    Linux下的多线程编程
  • 原文地址:https://www.cnblogs.com/panning/p/13665835.html
Copyright © 2011-2022 走看看