public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
//释放同步状态(锁)
int savedState = fullyRelease(node);
int interruptMode = 0;
//判断节点是否放入同步对列
while (!isOnSyncQueue(node)) {
//阻塞
LockSupport.park(this);
//如果已经中断了,则退出
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
分析上述方法的大概过程:
- 将当前线程创建为节点,加入等待队列;
- 释放锁,唤醒同步队列中的后继节点;
- while循环判断节点是否放入同步队列:
- 没有放入,则阻塞,继续 while 循环(如果已经中断了,则退出)
- 放入,则退出 while 循环,执行后面的判断
- 退出 while 说明节点已经在同步队列中,调用 acquireQueued() 方法加入同步状态竞争。
- 竞争到锁后从 await() 方法返回,即退出该方法。