LinkedBlockingQueue 与 ArrayBlockingQueue的区别 学习

队列是一个先进先出的数据结构

一、LinkedBlockingQueue     

          先来看看构造方法,首先是默认构造方法,不传入capacity时,调用但参数的构造方法。此时LinkedBlockingQueue是一个无界队列,因为默认传入的是Integer.MAX_VALUE。可以默认为无界。

  /**
     * Creates a {@code LinkedBlockingQueue} with a capacity of
     * {@link Integer#MAX_VALUE}.
       * 默认构造方法
     */
    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }

    /**
     * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
     *
     * @param capacity the capacity of this queue
     * @throws IllegalArgumentException if {@code capacity} is not greater
     *         than zero
     */
    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

    /**
     * Creates a {@code LinkedBlockingQueue} with a capacity of
     * {@link Integer#MAX_VALUE}, initially containing the elements of the
     * given collection,
     * added in traversal order of the collection's iterator.
     *
     * @param c the collection of elements to initially contain
     * @throws NullPointerException if the specified collection or any
     *         of its elements are null
     */
    public LinkedBlockingQueue(Collection<? extends E> c) {
        this(Integer.MAX_VALUE);
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        try {
            int n = 0;
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (n == capacity)
                    throw new IllegalStateException("Queue full");
                enqueue(new Node<E>(e));
                ++n;
            }
            count.set(n);
        } finally {
            putLock.unlock();
        }
    }

(1)故名思意,底层是由链表实现。实现链表类为:Node

成员变量有count

/** Current number of elements */
//主要用于记录当前链表长度
private final AtomicInteger count = new AtomicInteger();

/** Lock held by take, poll, etc */
//使用显示锁,及Condition通知。
private final ReentrantLock takeLock = new ReentrantLock();

/** Wait queue for waiting takes */
//用于take方法,队列为空时,await()阻塞等待,在添加元素后,会signal()解开
private final Condition notEmpty = takeLock.newCondition();

/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();

/** Wait queue for waiting puts */
//用于put方法放入元素,队列元素等于设置的长度时,await()阻塞等待,删除元素后,会signal()解开
private final Condition notFull = putLock.newCondition();

(2)常用方法

方法作用
boolean add(E e)
在此qeque的末尾插入指定的元素,除非它会违反容量限制(容量不足时抛出IllegalStateException异常)。
boolean offer(E e)将指定的元素插入由此queue表示的队列(换句话说,在该queue的尾部),如果可以立即执行,而不违反容量限制, true在成功时 false如果当前没有可用空间,则返回false
boolean offer(E e, long timeout, TimeUnit unit)将指定的元素插入由此queue表示的队列中(换句话说,在该queue的尾部),等待指定的等待时间(如果需要空间可用),会造成阻塞。
void clear()从这个queue原子地删除所有的元素。
E remove()检索并删除由此queue表示的队列的头部。
E take()检索并删除由此queue(换句话说,该queue的第一个元素)表示的队列的头部,如果需要,等待,直到元素可用。
E peek() 检索但不删除由此queue表示的队列的头部(换句话说,此queue的第一个元素),如果此queue为空,则返回 null 。  
E poll()检索并删除由此queue表示的队列的头部(换句话说,该queue的第一个元素),如果此queue为空,则返回 null 。
E poll(long timeout, TimeUnitunit)检索并删除由此queue(换句话说,该queue的第一个元素)表示的队列的头部,等待到指定的等待时间(如有必要)使元素变为可用
int size() 返回此queue中的元素数
boolean contains(Object o)如果此queue包含指定的元素,则返回 true
E pop() 从这个queue表示的堆栈中弹出一个元素。
void push(E e)将元素推入此双端队列表示的堆栈(换句话说,在该双端队列的头部),如果它是立即可行且不会违反容量限制,抛出IllegalStateException如果当前没有空间可用。 
void put(E e)将指定的元素插入由此queue表示的队列(换句话说,在该queue的尾部),等待空格变为可用时。

(3)常用方法分析

1、先来看看添加方法:

enqueue方法:

/**
 * Links node at end of queue.
 *
 * @param node the node
 */
private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    //等于:last.next = node; 将链表最后元素指向最新插入的元素,同时将last地址指向新插入元素
    //   last = node;
    last = last.next = node;
}

 

offer方法:

//将指定的元素插入由此queue表示的队列(换句话说,在该queue的尾部),如果可以立即执行,而不违反容量限制, true在成功时 false如果当前没有可用空间,则返回false
public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    //当前元素等于设定长度后,也就是没有可用空间,返回false
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    //加锁添加元素
    putLock.lock();
    try {
        if (count.get() < capacity) {
             //添加元素的具体方法
            enqueue(node);
            //让原子类count自增+1
            c = count.getAndIncrement();
            if (c + 1 < capacity)
               //若元素不满,尝试唤醒由put方法,在元素满时休眠的线程(若没休眠,执行方法也可)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        // 添加进入元素,唤醒由take阻塞的线程
        //  private void signalNotEmpty() {
        //    final ReentrantLock takeLock = this.takeLock;
        //    takeLock.lock();
        //    try {
        //       notEmpty.signal();
        //    } finally {
        //       takeLock.unlock();
        //    }
        // }
        signalNotEmpty();
    return c >= 0;
}

add方法:

//若offer返回false,直接抛出异常
public boolean add(E e) {
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

put方法:

//将指定的元素插入由此queue表示的队列(换句话说,在该queue的尾部),等待空格变为可用时。
public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
       //当添加元素已满时,阻塞,当前添加的元素一直阻塞到队列空出一个位置为止
        while (count.get() == capacity) {
            notFull.await();
        }
        //同样添加队列,给数量新增1
        enqueue(node);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

2、再来看看弹出方法,和添加类似

dequeue:

//因为是队列,先进先出,所以从链表头取出元素
private E dequeue() {
    // assert takeLock.isHeldByCurrentThread();
    // assert head.item == null;
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h; // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}

take方法:

//检索并删除由此queue(换句话说,该queue的第一个元素)表示的队列的头部,如果需要,等待,直到元素可用。
public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
   //加锁从链表中取出数据
    takeLock.lockInterruptibly();
    try {
        //如果数据数量为0,则需要一直等待到链表中有数据加入为止
        while (count.get() == 0) {
            notEmpty.await();
        }
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
//唤醒由put添加为满时阻塞的线程      
//     private void signalNotFull() {
//       final ReentrantLock putLock = this.putLock;
//       putLock.lock();
//       try {
//          notFull.signal();
//       } finally {
//          putLock.unlock();
//       }
//    }
        signalNotFull();
    return x;
}

poll()方法:

//检索并删除由此queue表示的队列的头部(换句话说,该queue的第一个元素),如果此queue为空,则返回 null 。
public E poll() {
    final AtomicInteger count = this.count;
    //如果队列为空,返回null,不像take会阻塞
    if (count.get() == 0)
        return null;
    E x = null;
    int c = -1;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        if (count.get() > 0) {
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        }
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

一、ArrayBlockingQueue

       这是一个底层由数组构成,先来看看构造方法。因为不准不传入capacity,队列长度的参数,所以这是一个有界的队列,当然要是定义的很长,那也可以算无界了。

 /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and default access policy.
     *
     * @param capacity the capacity of this queue
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and the specified access policy.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }
在Array中,队列的长度不像Linked使用原子类来保存,而是直接使用count,这是因为array中,count的增加与减少都是在锁中进行的
/** Number of elements in the queue */
int count;
同样使用显示锁来控制元素的插入取出
/** Main lock guarding all access */
final ReentrantLock lock;

/** Condition for waiting takes */
private final Condition notEmpty;

/** Condition for waiting puts */
private final Condition notFull;

 

2、常用方法

方法作用

boolean add(E e) 
在插入此队列的尾部,如果有可能立即这样做不超过该队列的容量,返回指定的元素 true成功时与抛出 IllegalStateException如果此队列已满。
void put(E e) 在该队列的尾部插入指定的元素,如果队列已满,则等待空间变为可用。
boolean offer(E e) 如果可以在不超过队列容量的情况下立即将其指定的元素插入该队列的尾部,则在成功时 false如果该队列已满,则返回 true 。
boolean offer(E e, long timeout, TimeUnit unit)在该队列的尾部插入指定的元素,等待指定的等待时间,以使空间在队列已满时变为可用。  
E peek() 检索但不删除此队列的头,如果此队列为空,则返回 null 。
E poll() 检索并删除此队列的头,如果此队列为空,则返回 null 。
E poll(long timeout, TimeUnit unit) 检索并删除此队列的头,等待指定的等待时间(如有必要)使元素变为可用。 
E take() 检索并删除此队列的头,如有必要,等待元素可用。  
从这个队列中原子地删除所有的元素。  
boolean contains(Object o) 如果此队列包含指定的元素,则返回 true 。 
int size()返回此队列中的元素数。

3、常用方法分析

(1)添加方法

enqueue:

//数组入队
private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x;
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    notEmpty.signal();
}

offer方法:

//如果可以在不超过队列容量的情况下立即将其指定的元素插入该队列的尾部,则在成功时 false如果该队列已满,则返回 true 。
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();
    }
}

put方法:

//和offer方法不一样的是,在该队列的尾部插入指定的元素,如果队列已满,则等待空间变为可用。
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();
    }
}

(2)取出方法

dequeue:

//队列先进先出,从数组的头部取出数据
private E dequeue() {
    // assert lock.getHoldCount() == 1;
    // assert items[takeIndex] != null;
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex];
    items[takeIndex] = null;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    notFull.signal();
    return x;
}

take方法:

//检索并删除此队列的头,如有必要,等待元素可用。  从这个队列中原子地删除所有的元素。  
public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}

poo方法:

//检索并删除此队列的头,如果此队列为空,则返回 null 。
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return dequeue();
    } finally {
        lock.unlock();
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值