new ReentrantLock(true);加锁流程:
protected final boolean tryAcquire(int acquires) {
//获取以后线程
final Thread current = Thread.currentThread();
//获取state值
int c = getState();
//还没有线程占用
if (c == 0) {
//!(头节点和尾节点不是一个节点 && (头节点的next -> NULL 或者 头节点.next节点 不是 以后线程 ))
//也就是说,头尾是一个节点 或者 头节点.next节点的线程是以后线程
if (!hasQueuedPredecessors() &&
//cas 0 -> 1
compareAndSetState(0, acquires)) {
/设置独占线程
setExclusiveOwnerThread(current);
return true;
}
}
//以后线程等于独占线程
else if (current == getExclusiveOwnerThread()) {
//state值+1
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
//从新赋值 state 值
setState(nextc);
return true;
}
//否则返回false
return false;
}
如果取得锁失败,和JDK8 new ReentrantLock()加锁流程(一)中流程一样!
发表回复