Java “为什么?”;LinkedBlockingQueue“放置”;“需要”;notFull.signal();
JDK 1.8中Java “为什么?”;LinkedBlockingQueue“放置”;“需要”;notFull.signal();,java,multithreading,blockingqueue,linkedblockingqueue,Java,Multithreading,Blockingqueue,Linkedblockingqueue,JDK 1.8中LinkedBlockingQueue的put方法的源代码: 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 indicat
LinkedBlockingQueue
的put
方法的源代码:
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();
if (c + 1 < capacity)
notFull.signal(); // Is this necessary?
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
public void put(E)抛出InterruptedException{
如果(e==null)抛出新的NullPointerException();
//注:所有put/take/etc中的惯例是预设本地var
//除非设置,否则保持计数为负数表示失败。
int c=-1;
节点=新节点(e);
final ReentrantLock putLock=this.putLock;
最终原子整数计数=this.count;
locklock.lockly();
试一试{
/*
*注意,count在wait-guard中使用,即使它是
*不受锁保护。这是因为计数可以
*仅在此点减少(所有其他PUT均关闭
*我们(或其他等待着的人)是
*如果容量发生变化,则发出信号。类似
*用于其他等待保护中计数的所有其他用途。
*/
while(count.get()=容量){
未满。等待();
}
排队(节点);
c=count.getAndIncrement();
如果(c+1<容量)
notFull.signal();//这是必需的吗?
}最后{
putLock.unlock();
}
如果(c==0)
signalNotEmpty();
}
为什么当前生产者需要通过
notFull.signal()
唤醒其他生产者,而消费者在从队列中获取元素后会这样做?有什么例子可以解释这是必要的吗?我不确定这是否可行
notFull.await()处阻塞代码>
putLock
,P2必须等待。不幸的是,P2在等待时超时