- 读锁加锁:没有线程持有锁,或者持有的都是读锁
- 写锁加锁:没有线程持有锁
写锁
加锁
public void lock() {
sync.acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
Thread current = Thread.currentThread();
int c = getState();
int w = exclusiveCount(c); //AQS状态中独占锁的数目
if (c != 0) { //有线程持有锁
//(1)没有独占锁全是共享锁时,加锁失败
//(2)存在独占锁且不是当前线程持有时,加锁失败
if (w == 0 || current != getExclusiveOwnerThread())
return false;
//独占锁阈值限制
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// Reentrant acquire
setState(c + acquires);
return true;
}
//阻塞场景,比如公平锁场景当前线程在AQS队列中有前驱节点
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;
//可重入锁状态设置
setExclusiveOwnerThread(current);
return true;
}
解锁
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h); //唤醒节点
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
if (!isHeldExclusively()) //没有线程持有锁,抛错
throw new IllegalMonitorStateException();
int nextc = getState() - releases; //状态扣减
boolean free = exclusiveCount(nextc) == 0;
if (free) //状态归零,已经没有线程持有锁
setExclusiveOwnerThread(null);
setState(nextc);
return free;
}
读锁
加锁
同写锁的加锁