/** * Inserts the specified element at the tail of this queue, waiting * for space to become available if the queue is full. * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ publicvoidput(E e)throws InterruptedException { checkNotNull(e); finalReentrantLocklock=this.lock; lock.lockInterruptibly(); try { while (count == items.length) notFull.await(); // 如果队列已满,则等待 insert(e); } finally { lock.unlock(); } }
/** * Inserts element at current put position, advances, and signals. * Call only when holding lock. */ privatevoidinsert(E x) { items[putIndex] = x; putIndex = inc(putIndex); ++count; notEmpty.signal(); // 有新的元素被插入,通知等待中的取走元素线程 }
public E take()throws InterruptedException { finalReentrantLocklock=this.lock; lock.lockInterruptibly(); try { while (count == 0) notEmpty.await(); // 如果队列为空,则等待 return extract(); } finally { lock.unlock(); } }
/** * Extracts element at current take position, advances, and signals. * Call only when holding lock. */ private E extract() { final Object[] items = this.items; Ex=this.<E>cast(items[takeIndex]); items[takeIndex] = null; takeIndex = inc(takeIndex); --count; notFull.signal(); // 有新的元素被取走,通知等待中的插入元素线程 return x; }