Condition接口也是JUC的lock包下的一个基础接口,在AQS内部实现了Condition的实现类ConditionObject。
既然是AQS的内部类,那么要使用Condition的前置条件就需要先lock.lock获取锁,这样AQS中的抽象接口才能有实现。
锁+Condition也可以根据signal和await实现生产消费模型,这种方式比synchronize的好处在于可以实现基于不同条件的精确唤醒。
原理就是每个Condition都实现了一个等待队列,这样一个对象就包含一个AQS同步队列+多个Condition等待队列。
Condition的await等待本质就是将线程节点从同步队列中移除,然后加入到等待队列中;
signal唤醒本质就是将等待队列中的头节点线程,移动到同步队列中,然后唤醒该线程,让该线程参与同步状态的竞争。
Condition接口
在使用Lock接口之前,我们使用synchronized关键字来实现同步,加上Object中的wait、notify接口来实现等待-通知模式。
Condition接口提供了与ObjectMonitor类似的接口功能,加上Lock也可以实现等待-通知模式。两者之间的对比:
对比 | ObjectMonitor | Condition |
---|---|---|
前置条件 | 获取对象锁 | 调用Lock.lock获取锁;调用Lock.newCondition获取Condition对象 |
调用方式 | 直接调用,如:object.wait() | 直接调用,如condition.await() |
等待队列个数 | 一个 | 多个 |
当前线程释放锁并进入等待状态 | 支持 | 支持 |
等钱线程释放锁并进入等待状态,在等待状态中不响应中断 | 不支持 | 支持 |
当前线程释放锁并进入超时等待状态 | 支持 | 支持 |
当前线程释放锁并进入等待状态到将来的某个时间 | 不支持 | 支持 |
唤醒等待队列中的一个线程 | 支持 | 支持 |
唤醒等待队列中的全部线程 | 支持 | 支持 |
接口中的方法:
public interface Condition {
void await() throws InterruptedException;
void awaitUninterruptibly();
long awaitNanos(long nanosTimeout) throws InterruptedException;
boolean await(long time, TimeUnit unit) throws InterruptedException;
boolean awaitUntil(Date deadline) throws InterruptedException;
void signal();
void signalAll();
}
Condition+Lock实现生产者-消费者模型
public class storage{
public static final int MAX_COUNT = 10;
private LinkedList<Object> list = new LinkedList<Object>();
private final Lock lock = new ReentrantLock();
//有两个condition条件,可以让生产者线程和消费者线程同时执行,相对于synchronized
private final Condition fullCon = lock.newCondition();
private final Condition emptyCon = lock.newCondition();
public void producer(){
lock.lock();
while(list.size() == MAX_COUNT){
fullCon.await();
}
list.add(new Object());
emptyCon.signalAll();
lock.unlock();
}
public void consumer(){
lock.lock();
while(list.size() == 0){
emptyCon.await();
}
list.remove();
fullCon.signalAll();
lock.unlock();
}
}
与【并发编程】(二)Java并发机制底层实现原理——synchronized关键字中的wait/notify实现生产者-消费者模型相对比:
- synchronized不能绑定锁的条件;
- ReentrantLock通过绑定Condition结合await()/singal()方法实现线程的 精确唤醒 ,而不是像synchronized通过Object类的wait()/notify()/notifyAll()方法要么随机唤醒一个线程要么唤醒全部线程;
Condition原理分析——等待队列与同步队列
Condition是AQS的内部类,每个Condition对象都包含一个 等待队列 。
在Lock锁的机制下,一个对象可以拥有 一个同步队列、多个等待队列 ,与传统的Object Monitor不同,condition可以伴随不同的条件。
- 同步队列与等待队列之间的关系可以表示为:
- 等待:
调用Condition.await方法,当前线程
- 构造新的节点,加入等待队列
- 释放锁
- 通知:
调用Condition.signal方法,当前线程:
- 把等待队列的首节点移到同步队列的尾部
- 唤醒该节点
- (并不代表该线程就获取到了锁,它需要加入到锁的竞争acquireQueued方法中,只有成功获取到锁,才能从await方法返回)
存储结构与构造函数
public class ConditionObject implements Condition, java.io.Serializable {
/** First node of condition queue. */
private transient Node firstWaiter;
/** Last node of condition queue. */
private transient Node lastWaiter;
/**
* Creates a new {@code ConditionObject} instance.
*/
public ConditionObject() { }
}
两个指针firstWaiter和lastWaiter分别指向等待队列的头部和尾部。
Condition.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
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
- 将当前线程加入等待队列
- 释放锁,同时将线程从同步队列中移除,并唤醒同步队列中的下一个节点
- 判断当前线程节点是否还在同步队列中,如果不在则阻塞线程
- 当线程被唤醒后,重新在同步队列中与其他线程竞争获取同步状态
1. addConditionWaiter将同步队列中需要等待的线程加入到等待队列中
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;
}
- new Node(Thread.currentThread(), Node.CONDITION)构建等待节点
- 修改firstWaiter、lastWaiter的指向
2.fullyRelease释放锁
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;
}
}
3. 循环判断isOnSyncQueue:当前线程节点是否在同步队列中
final boolean isOnSyncQueue(Node node) {
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
if (node.next != null) // If has successor, it must be on queue
return true;
/*
* node.prev can be non-null, but not yet on queue because
* the CAS to place it on queue can fail. So we have to
* traverse from tail to make sure it actually made it. It
* will always be near the tail in calls to this method, and
* unless the CAS failed (which is unlikely), it will be
* there, so we hardly ever traverse much.
*/
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;
}
}
- 因为同步队列中的Node才使用pre、next指针,所以先利用这两个字段是否为null简单判断其是否在同步队列中;
- 如果需要阻塞的线程节点还没有加入到同步队列中,则需要遍历同步队列来判断是该线程节点是否已存在;
- 如果最终判断不在同步队列里,通过LockSupport.park(this);阻塞当前线程。
4. 出循环表示当前节点在同步队列(已被唤醒),acquireQueued重新与同步队列中其他节点竞争
Condition.signal 唤醒
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
- 通过isHeldExclusively()方法,判断当前线程是否获取到了同步状态(也就是锁)。
- 通过doSignal(Node first)方法,获取等待队列中的首节点,然后将其移动到同步队列,然后再唤醒该线程节点。
1. isHeldExclusively判断当前线程是否获取到了锁
protected boolean isHeldExclusively() {
throw new UnsupportedOperationException();
}
//在ReentrantLock中的实现:
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
2. doSignal将等待队列首节点加入同步队列,并唤醒
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
- first节点为等待队列的首节点
- 将等待队列中的首节点从等待队列中移除,并设置firstWaiter的指向为首节点的下一个节点。
- 通过 transferForSignal(Node node)方法,将等待队列中的首节点,加入到同步队列中去,然后重新唤醒该线程节点。
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).
*/
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
总结
等待
- 将该线程节点从同步队列中移除,并释放其同步状态。
- 构造新的阻塞节点,加入到等待队列中。
唤醒
- 将等待队列中的头节点线程,移动到同步队列中。
- 当移动到同步队列后,唤醒该线程,让该线程参与同步状态的竞争。