文章目录
可重入原理
- 可重入原理
- 加锁
- 解锁
- 可打断原理
- 不可打断模式
- 可打断模式
- 条件变量实现原理
- await流程
- addConditionWaiter()
- fullyRelease ()
- park()
- signal 流程
- isHeldExclusively()
- doSignal ()
- transferForSignal ()
- unlock 流程
仍然以非公平锁为例
加锁/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
*/
// Sync的方法
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
// 如果已经获得了锁, 线程还是当前线程, 表示发生了锁重入
else if (current == getExclusiveOwnerThread()) {
//state++
int nextc = c + acquires;
if (nextc 0或者cas失败 唤醒Thread-0
LockSupport.unpark(node.thread);
return true;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;//此时同步队列尾指针指向的是Thread-3
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;//Thread-0的前指针指向Thread-3
if (compareAndSetTail(t, node)) {//同步队列尾指针指向Thread-0
t.next = node;//Thread-3的后指针指向Thread-0
return t;//返回Thead-3
}
}
}
}
接着Thread-1 会释放锁,进入 unlock 流程,然后唤醒Thread-2去尝试获取锁
unlock释放锁的流程已经在从ReentrantLock源码解读AQS中讲解过了,这里就不再继续赘述了。