标签:非公平锁 version 控制 object 对象 基本 syn next false
从上图可以看出,ReentrantLock的功能都是通过sync这个对象提供的。
public class ReentrantLock implements Lock, java.io.Serializable {
private final Sync sync;
}
/**
* 锁的同步控制的基础,抽象类提供了基本处理框架,具体逻辑由子类实现
* 使用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;
}
}
标签:非公平锁 version 控制 object 对象 基本 syn next false
原文地址:https://www.cnblogs.com/zerodsLearnJava/p/12744370.html