文章目录
前言
以Condition模拟了生产者消费者场景,基于如下代码分析。
public class SourceAnalyze {
// 初始化资源
private volatile static int i = 0;
public static void main(String[] args) {
// 锁
ReentrantLock lock = new ReentrantLock();
// 生产者队列
Condition c1 = lock.newCondition();
// 消费者队列
Condition c2 = lock.newCondition();
// 生产者线程
new Thread(() -> {
while (true) {
// 由于生产者和消费者之间会抢夺资源,所以先加锁
lock.lock();
// 资源已经满了
if (i == 1) {
try {
// 生产者先停产,等等唤醒
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 生产资源
i++;
System.out.println(Thread.currentThread().getName() + "生产==========" + i);
// 有资源可以消费了,唤醒消费者
c2.signal();
// 解锁
lock.unlock();
}
}).start();
// 消费者线程
new Thread(() -> {
while (true) {
// 加锁
lock.lock();
// 没有资源可以消费
if (i == 0) {
try {
// 消费者停止消费
c2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 消费
i--;
System.out.println(Thread.currentThread().getName() + "消费==========" + i);
// 唤醒生产者,可以开始生产
c1.signal();
// 解锁
lock.unlock();
}
}).start();
while (true) {
}
}
}
输出如下:
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
Thread-0生产1
Thread-1消费0
一、Conditioin
进入同步队列,等待被唤醒
1、await
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
// 将失效的同步节点从同步任务对列取下包括当前节点(当前节点已经不是Condition)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
1.1、addConditionWaiter
添加到任务等待队列-Condition
private Node addConditionWaiter() {
// 获取队列最后一个节点啊
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
// 清楚被取消的节点
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters();
t = lastWaiter;
}
// 实例化节点 将节点放到队列最后一个
Node node = new Node(Thread.currentThread(), Node.CONDITION);
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
1.2、fullyRelease
释放当前任务持有的锁
final int fullyRelease(Node node) {
boolean failed = true;
try {
// 获取当前持有的资源
int savedState = getState();
// 释放资源(参考Lock)
if (release(savedState)) {
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
1.3、isOnSyncQueue
判断当前节点是否在同步队列-Lock
final boolean isOnSyncQueue(Node node) {
// 当前任务节点状态为Condition 当前节点的prev节点为null(同步队列的prev节点是head) 则不在队列
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
// 同步队列有next节点的
if (node.next != null) // If has successor, it must be on queue
return true;
return findNodeFromTail(node);
}
// 变量同步队列,看下当前节点是否有在
private boolean findNodeFromTail(Node node) {
Node t = tail;
for (;;) {
if (t == node)
return true;
if (t == null)
return false;
t = t.prev;
}
}
1.4、unlinkCancelledWaiters
将失效的同步任务从同步队列中取下-Condition
private void unlinkCancelledWaiters() {
// 第一个节点
Node t = firstWaiter;
// 当前同步队列最后一个节点,临时变量
Node trail = null;
while (t != null) {
Node next = t.nextWaiter;
// 节点任务状态不是同步状态
if (t.waitStatus != Node.CONDITION) {
t.nextWaiter = null;
if (trail == null)
firstWaiter = next;
else
trail.nextWaiter = next;
if (next == null)
lastWaiter = trail;
}
else
trail = t;
t = next;
}
}
2、singalAll
唤醒其它同步队列的任务
// Sync.lock
public final void signal() {
// 如果当前线程没有持有锁,抛出异常
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
// 唤醒第一个等待的任务
if (first != null)
doSignal(first);
}
2.1、doSignal
唤醒队列中等待状态的任务直到唤醒成功一个或者任务队列为null
private void doSignal(Node first) {
do {
// 持续唤醒第一个任务直到成功
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
2.1、transferForSignal
将当前任务从任务队列放到同步队列-参考await的isOnSyncQueue
final boolean transferForSignal(Node node) {
/*
* 将任务状态换为0-
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* 放入节点到同步队列
*/
Node p = enq(node);
int ws = p.waitStatus;
// 如果设置状态失败 直接唤醒等待线程 而不是等同步队列唤醒
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
二、总结
Condition内部基于任务在任务队列到同步队列之间转换