ReentrantLock
Posted zerodslearnjava
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReentrantLock相关的知识,希望对你有一定的参考价值。
ReentrantLock
1 数据结构
从上图可以看出,ReentrantLock的功能都是通过sync这个对象提供的。
public class ReentrantLock implements Lock, java.io.Serializable {
private final Sync sync;
}
2 获取锁是否要走公平非公平逻辑
- 区分公平非公平锁,公平锁老实排队
- lock
- lockInterruptibly
- tryLock(long timeout, TimeUnit unit)
- 不区分是否公平,如果锁可获取就去竞争
- tryLock()
3 源码解析
/**
* 锁的同步控制的基础,抽象类提供了基本处理框架,具体逻辑由子类实现
* 使用AQS的状态作为持有锁的数目
*/
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
abstract void lock();
// 执行非公平trylock
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()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
// 释放
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
// 检查当前线程是不是持有锁
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
// 条件
final ConditionObject newCondition() {
return new ConditionObject();
}
// 获取持有锁的线程
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
// 获取持有锁的次数
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
// 是否加锁了
final boolean isLocked() {
return getState() != 0;
}
}
以上是关于ReentrantLock的主要内容,如果未能解决你的问题,请参考以下文章