前置知识:Lock锁的实现原理,AQS
Await
public class ConditionObject implements Condition, java.io.Serializable {
//队列头
private transient Node firstWaiter;
//队列尾
private transient Node lastWaiter;
//.......省略
}
当前线程进入等待
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//加入等待队列
Node node = addConditionWaiter();
//完全释放锁,Lock锁是可重入锁,可能被一个线程多次进入。
long savedState = fullyRelease(node);
int interruptMode = 0;
//是否在同步队列中,await一直为false
while (!isOnSyncQueue(node)) {
//阻塞当前线程,线程配唤醒从这里开始继续执行。
//sigal唤醒线程会将Node加入AQS队列,状态更改为0
//唤醒之后while循环结束
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
//获取锁
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
//移除的获取锁的节点,并清理节点状态不是Condition的节点
//signalAll会把等待队列所有node 通过enq入队AQS。
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
加入waiter队列
private Node addConditionWaiter() {
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
//清理取消的尾节点
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters();
t = lastWaiter;
}
//创建节点
//设置节点状态为condition
Node node = new Node(Thread.currentThread(), Node.CONDITION);
//初始化头节点或尾插入
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
完全释放锁
final int fullyRelease(Node node) {
boolean failed = true;
try {
//获取锁状态
int savedState = getState();
//释放锁
if (release(savedState)) {
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
//调用await线程,必须是当前持有锁的线程
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
//锁持有人设为null
setExclusiveOwnerThread(null);
}
//设置锁状态哦
setState(c);
return free;
}
SignalAll
public final void signalAll() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
//唤醒所有
doSignalAll(first);
}
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
//处理所有Node
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
final boolean transferForSignal(Node node) {
//修改 waitStatus == 0
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* 加入队列,返回当前节点的prev节点
*/
Node p = enq(node);
int ws = p.waitStatus;
//设置前一个节点为 SIGNAL
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}