// ReentrantLock.FairSync::initialTryLock
final boolean initialTryLock() {
Thread current = Thread.currentThread();
int c = getState();
// c==0说明当前锁无人获取
if (c == 0) {
// hasQueuedThreads()==false说明当前线程排在队首,此时才能进行cas操作,否则不公平
if (!hasQueuedThreads() && compareAndSetState(0, 1)) {
setExclusiveOwnerThread(current);
return true;
}
// 锁已经被当前线程获取,这次获取为重入,与Sync::tryLock逻辑一样
} else if (getExclusiveOwnerThread() == current) {
if (++c < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(c);
return true;
}
return false;
}