为了账号安全,请及时绑定邮箱和手机立即绑定

为何ArrayBlockingQueue中的ReentranLock对象无需实例化?

public class ArrayBlockingQueue<E> extends AbstractQueue<E>        
implements BlockingQueue<E>, java.io.Serializable {

    final Object[] items;      
    int takeIndex;      
    int putIndex;       
    int count;        
    final ReentrantLock lock;    /**notEmpty条件对象,用于通知take方法队列已有元素,可执行获取操作 */
    
    private final Condition notEmpty;        
    private final Condition notFull;          迭代器     */    
    transient Itrs itrs = null;
    
    public void put(E e) throws InterruptedException {     
    checkNotNull(e);           
    final ReentrantLock lock = this.lock;  // ????????      
    lock.lockInterruptibly();
    try {                    
         while (count == items.length)              //将当前调用线程挂起,添加到notFull条件队列中等待唤醒              
         notFull.await();          
         enqueue(e);//如果队列没有满直接添加。。      } finally {          
           lock.unlock();      
               }  
            }
         }

为甚么类的属性里没有ReentrantLock lock = new ReentrantLock();

却可以在put()中直接指定ReentrantLock lock=this.lock;?


正在回答

1 回答

/**
 * 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();
}

构造方法里面初始化了lock对象


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为何ArrayBlockingQueue中的ReentranLock对象无需实例化?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号