ConditionObject源码剖析
ConditionObject源码剖析
这玩意是AQS的一个内部类。
案例演示:
public class ReentrantLockConditionDemo {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// 可以有多个条件
//Condition condition2 = lock.newCondition();
//Condition condition3= lock.newCondition();
public static void main(String[] args) {
ReentrantLockConditionDemo demo = new ReentrantLockConditionDemo();
new Thread(demo::task1).start();
new Thread(demo::task2).start();
}
private void task1() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " task1 加锁成功");
System.out.println(Thread.currentThread().getName() + " task1 执行await被挂起");
condition.await();
System.out.println(Thread.currentThread().getName() + " task1 被唤醒成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " task1 释放锁成功");
}
}
private void task2() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " task2 加锁成功");
condition.signal();
System.out.println(Thread.currentThread().getName() + " task2 唤醒 task1");
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " task2 释放锁成功");
}
}
}
运行结果:
Thread-0 task1 加锁成功
Thread-0 task1 执行await被挂起
Thread-1 task2 加锁成功
Thread-1 task2 唤醒 task1
Thread-1 task2 释放锁成功
Thread-0 task1 被唤醒成功
Thread-0 task1 释放锁成功
数据结构:
ConditionObject是一个单向链表。
ConditionObject关键属性和方法介绍:
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** First node of condition queue. */
// 等待队列的⾸节点
private transient Node firstWaiter;
/** Last node of condition queue. */
// 等待队列的尾结点
private transient Node lastWaiter;
// 挂起方法
public final void await() throws InterruptedException {
// 如果当前线程被中断,则抛出异常
if (Thread.interrupted())
throw new InterruptedException();
// 新增⼀个新的节点信息,成功后返回该节点,节点类型依然是Node类型,但是节点的waitStatus是-2
Node node = addConditionWaiter();
// 释放当前线程所拥有的锁,并返回同步状态
int savedState = fullyRelease(node);
int interruptMode = 0;
// 在循环⾥⼀直检查当前阻塞的队列是否已经被唤醒,
// 如果已经被唤醒,则跳出 while 循环
// 判断node是否处于阻塞队列
while (!isOnSyncQueue(node)) {
// 如果当前线程不再同步队列中,则进⾏阻塞,等待被唤醒
LockSupport.park(this);
// 阻塞的同时,不断的检查当前节点是否被中断,如果被中断,则结束检查
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
// 当前线程已经被唤醒,通过调⽤acquireQueued⽅法加⼊到获取同步状态的竞争中
// 说白了就是加入到AQS的双向链表中,等待被执行
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;
if (first != null)
doSignal(first); // 点进去,见下
}
// 真正的唤醒方法
private void doSignal(Node first) {
do {
// firstWaiter 头节点指向条件队列头的下⼀个节点
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.
*/
// 判断节点是否已经在之前被取消了
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).
*/
// 调⽤ enq 添加到 同步队列的尾部
// enq ⽅法详⻅ AQS 解析的 enq ⽅法
Node p = enq(node);
int ws = p.waitStatus;
// node 的上⼀个节点 修改为 SIGNAL 这样后续就可以唤醒⾃⼰了
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
}
总结:aqs中维护了两个链表,一个是AQS双向链表,一个或多个ConditionObject的单项链表,多个单项链表之间相互不影响。