final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread(); // 获得当前线程int c = getState(); // 获取锁的状态值
if (c == 0) { // 如果锁未被占用,则获得该锁
if (compareAndSetState(0, acquires)) { // cas机制,多线程抢占锁,谁RP好,谁获得锁
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;
}
方法尝试为当前线取排它的获取非公平锁,如果当前线程未获得锁,则对线程进行锁定,如果线程已获得锁,则状态值+1,如果锁被占用,则返回false。
protected final boolean tryRelease(int releases) {
int c = getState() - releases; // 减去释放值后的状态值
if (Thread.currentThread() != getExclusiveOwnerThread()) // 判断时候在同一个线程
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) { // 如果状态值为0,则释放锁
free = true;
setExclusiveOwnerThread(null);
}
setState(c); // 如果状态值不为0,设置减去释放值后的状态值
return free;
}
尝试释放当前锁,如果状态值为0则释放锁,如果不为0返回false。
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
// 判断当前线程是否拥有该锁
return getExclusiveOwnerThread() == Thread.currentThread();
}
在排它模式下,状态是否被占用。
final ConditionObject newCondition() {
return new ConditionObject();
}
Lock中通过Condition实现wait和notify,该方法用于创建一个Condition。
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
返回控制锁的线程,如果存在线程。
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
如果线程占用了锁,则返回锁的状态值,否则返回0。
final boolean isLocked() {
return getState() != 0;
}
判断锁是否被占用,返回boolean。
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
方法从该流中读取当前类的非静态和非瞬态字段。这也许只能称为从类反序列化readObject方法。它会抛出NotActiveException如果它被调用。并重置状态值。