ArrayBlockingQueue源码阅读
2016-08-12 21:18
495 查看
//阻塞式数组队列 public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable { //存放元素数组 final Object[] items; /** items index for next take, poll, peek or remove */ int takeIndex; /** items index for next put, offer, or add */ int putIndex; //队列中元素数量 int count; //可重入锁 final ReentrantLock lock; /** Condition for waiting takes */ private final Condition notEmpty; /** Condition for waiting puts */ private final Condition notFull; //添加元素,当队列满时,等待 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(); } } private void enqueue(E x) { final Object[] items = this.items; items[putIndex] = x; // 放入后存元素的索引等于数组长度,表示已满 if (++putIndex == items.length) putIndex = 0; count++; // 唤醒在notEmpty条件上等待的线程 notEmpty.signal(); } //取元素,当队列为空时,会阻塞一直等待 public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0)//队列数组元素个数为0,阻塞等待 notEmpty.await(); return dequeue(); } finally { lock.unlock(); } } private E dequeue() { 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条件上等待的线程 notFull.signal(); return x; } }
相关文章推荐
- JDK 1.8 ArrayBlockingQueue 源码阅读(一)插入
- ArrayBlockingQueue 源码阅读与分析
- 阅读ArrayBlockingQueue源码了解如何利用锁实现BlockingQueue
- ArrayBlockingQueue源码阅读心得
- java1.7集合源码阅读:ArrayBlockingQueue
- java源码阅读之ArrayBlockingQueue
- ArrayBlockingQueue源码阅读与理解
- JDK 1.8 ArrayBlockingQueue 源码阅读(二)获取
- J.U.C并发框架源码阅读(八)ArrayBlockingQueue
- 《java.util.concurrent 包源码阅读》06 ArrayBlockingQueue
- ArrayBlockingQueue 源码阅读 问题(一)
- ArrayBlockingQueue源码分析
- ArrayBlockingQueue源码分析
- java阻塞队列ArrayBlockingQueue源码分析
- Java 并发 --- 阻塞队列之ArrayBlockingQueue源码分析
- ArrayBlockingQueue源码解读
- JDK1.8 ArrayBlockingQueue源码分析
- ArrayBlockingQueue源码解析
- 源码分析-ArrayBlockingQueue
- ArrayBlockingQueue源码分析