JDK8 new ReentrantLock((true)加锁流程
作者:子瞻
这篇文章主要介绍了java面试中常遇到的问题JDK8 new ReentrantLock((true)加锁流程示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
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()加锁流程中流程一样!
以上就是JDK8 new ReentrantLock((true)加锁流程的详细内容,更多关于JDK8 new ReentrantLock的资料请关注脚本之家其它相关文章!
