标签:class private 插入 相对 pre ant 成功 jdk interrupt
/** Lock held by take, poll, etc */ private final ReentrantLock takeLock = new ReentrantLock();//take锁 /** Wait queue for waiting takes */ private final Condition notEmpty = takeLock.newCondition();//生成一个take锁的绑定Condition实例 /** Lock held by put, offer, etc */ private final ReentrantLock putLock = new ReentrantLock();//put锁 /** Wait queue for waiting puts */ private final Condition notFull = putLock.newCondition();//put锁
public E take() throws InterruptedException { E x; int c = -1; final AtomicInteger count = this.count; final ReentrantLock takeLock = this.takeLock; takeLock.lockInterruptibly();//加锁,可以响应中断的锁 try { while (count.get() == 0) {//如果没有数据,一直等待 notEmpty.await();//等待put()操作的通知 } x = dequeue();//取得第一个数据 c = count.getAndDecrement();//数量减1,原子操作,因为会和put()函数同时访问count.注意:变量c是count减1前的值 if (c > 1) notEmpty.signal();//通知其他take操作 } finally { takeLock.unlock();//释放锁 } if (c == capacity) signalNotFull();//通知put()操作,已有空余空间 return x; }
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 { /* * Note that count is used in wait guard even though it is * not protected by lock. This works because count can * only decrease at this point (all other puts are shut * out by lock), and we (or some other waiting put) are * signalled if it ever changes from capacity. Similarly * for all other uses of count in other wait guards. */ while (count.get() == capacity) {//当数据满了时候 notFull.await();//等待 } enqueue(node);//插入数据 c = count.getAndIncrement();//更新数据,变量c是count加1前的值 if (c + 1 < capacity) notFull.signal();//有足够空间,通知其他线程 } finally { putLock.unlock();//释放锁 } if (c == 0) signalNotEmpty();//插入成功后,通知take操作取数据 }
标签:class private 插入 相对 pre ant 成功 jdk interrupt
原文地址:http://www.cnblogs.com/ten951/p/6212285.html