ReentrantLock源码系列
ReentrantLock源码解读(1)——CAS
ReentrantLock源码解读(2)——ReentrantLock源码与AQS
ReentrantLock源码解读(3)——Condition
Condition是除了object的await/notify之外的另一种信号机制,通常与ReentrantLock连用。先给给例子
public class LockTest implements Runnable{
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();
@Override
public void run() {
lock.lock();
try {
System.out.println("before await");
condition.await();
System.out.println("await end");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
LockTest test = new LockTest();
Thread thread = new Thread(test);
thread.start();
Thread.sleep(2000);
lock.lock();
condition.signal();
lock.unlock();
}
}
- 源码
从newCondition()开始看。
public Condition newCondition() {
return sync.newCondition();
}
...
final ConditionObject newCondition() {
return new ConditionObject();
}
最后只是new了一个ConditionObject对象,后续的await方法,notify方法都是这个类所带的。这个类是AQS的一个内部类。
/** First node of condition queue. */
private transient Node firstWaiter;
/** Last node of condition queue. */
private transient Node lastWaiter;
它里面也维护了一个node队列。
await
现在来看await方法。
/**
* Implements interruptible condition wait.
* <ol>
* <li> If current thread is interrupted, throw InterruptedException.
* <li> Save lock state returned by {@link #getState}.
* <li> Invoke {@link #release} with saved state as argument,
* throwing IllegalMonitorStateException if it fails.
* <li> Block until signalled or interrupted.
* <li> Reacquire by invoking specialized version of
* {@link #acquire} with saved state as argument.
* <li> If interrupted while blocked in step 4, throw InterruptedException.
* </ol>
*/
public final void await