ReentrantLock持有实现了AbstractQueuedSynchronizer的static内部类,而AbstractQueuedSynchronizer继承了AbstractOwnableSynchronizer,AbstractOwnableSynchronizer有个保存当前持有锁的线程的变量exclusiveOwnerThread。
/** * The current owner of exclusive mode synchronization. */ private transient Thread exclusiveOwnerThread;
看看ReentrantLock如何获取锁:
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
/**
* Returns the thread last set by {@code setExclusiveOwnerThread},
* or {@code null} if never set. This method does not otherwise
* impose any synchronization or {@code volatile} field accesses.
* @return the owner thread
*/
protected final Thread getExclusiveOwnerThread() {
return exclusiveOwnerThread;
}
所以,ReentrantLock是通过保存的持有锁的线程来判断获取锁的操作是重入的还是竞争的。
本文深入解析了ReentrantLock如何通过保存持有锁的线程来判断重入与竞争,详细介绍了其核心方法tryAcquire的实现,以及exclusiveOwnerThread变量的作用。

被折叠的 条评论
为什么被折叠?



