重入锁,独占式
一、ReentrantLock.lock()->sync.lock()
1、NonfairSync
final void lock() {
if (compareAndSetState(0, 1))//尝试修改状态,若成功说明没有线程修改过,获取锁
setExclusiveOwnerThread(Thread.currentThread());//设置当前线程
else
acquire(1);//失败,则变成公平锁
}
2、FairSync
final void lock() {
acquire(1);
}
3、AbstractQueuedSynchronizer.acquire(int arg)
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();//中断本线程
}
4、NonfairSync.tryAcquire(int acquires)
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
//if尝试修改状态获取锁
//else if 检查是否是本线程已经获取到了锁,是则状态+1
//else 获取失败
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;
}
5、FairSync.tryAcquire(int acquires)
//if尝试修改状态获取锁,比上面上方多一步校验
//即当前线程必须在AQS的同步队列的头结点,或者同步队列为空,这样来保证公平
//else if 检查是否是本线程已经获取到了锁,是则状态+1
//else 获取失败
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;
}
6、第3步的acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
addWaiter把当前线程包装成一个独占式(EXCLUSIVE)节点,CAS放到AQS的同步队列尾部,更新尾节点
acquireQueued自旋新加入的节点,尝试获取直到成功,返回true应该中断
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {//死循环
final Node p = node.predecessor();//获取本节点前节点
if (p == head && tryAcquire(arg)) {//如果前节点是头结点,则尝试修改状态
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
// true如果该线程应该阻塞 && true 如果线程被中断了,
//private final boolean parkAndCheckInterrupt() {
// LockSupport.park(this);//阻塞线程
// return Thread.interrupted();
//}
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
二、ReentrantLock.unlock()->sync.release(1)
1、AQS.release
//完全释放返回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;
}
//完全释放,state置为0,返回true
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;
}
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);//头结点waitStatus置为0
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;//从尾节点往前找到最靠前的,waitStatus<=0的,不等于头结点的节点
}
if (s != null)
LockSupport.unpark(s.thread);//唤醒
}