Object对象存在一组监视器
方法,如wait,notify
,与synchronized
关键字配合可以组建等待\通知
模式。相应的, Condition接口配合Lock,也可以实现等待\通知模式, Condition对象的创建依赖于Lock(lock.newCondition()
)
使用示例
伪代码
void conditionAwait(){
lock.lock()
try{
//释放锁,进入到等待队列中
//等待被signal唤醒或者被中断
//能够返回说明已经再次获取到锁
condition.await()
}finally{
lock.unlock()
}
}
.........................
void conditionSignal(){
lock.lock()
try{
//发出唤醒等待队列首节点(等待时间最长)的通知
condition.signal()
}finally{
lock.unlock()
}
}
await和signal的逻辑
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//将线程加入到等待队列末尾
Node node = addConditionWaiter();
//释放线程上的锁(释放同步态)
int savedState = fullyRelease(node);
int interruptMode = 0;
//1. 刚释放锁,node已经在等待队列的末尾了,这里肯定不在同步队列
//进入while循环,第一行,就park阻塞住
//2. 被另一个线程执行signal被唤醒,park返回,继续while条件判断
// 由于signal时会将等待队列的第一个节点加入到同步队列的末尾,所以while
//条件不满足,往下走
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
//成功获取到锁,acquireQueue才会返回,否则阻塞住
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
........................................................................
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
//对等待队列的第一个节点执行signal唤醒
if (first != null)
doSignal(first);
}
//将等待队列的首节点加入到同步队列的末尾
//可能CAS失败,这里死循环直至成功
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
//将节点加入到同步队列末尾
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
* 将节点置为初始态0
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* Splice onto queue and try to set waitStatus of predecessor to
* indicate that thread is (probably) waiting. If cancelled or
* attempt to set waitStatus fails, wake up to resync (in which
* case the waitStatus can be transiently and harmlessly wrong).
* 加入到同步队列末尾
*/
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
await方法示意图
signal方法示意图
一个Lock拥有一个同步队列和多个等待队列