ReentrantLock reentrantLock = new ReentrantLock();
创建一个非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}
调用的锁的lock方法
reentrantLock.lock();
调用NonfairSync的lock方法
final void lock() {
// state是否等于0,等于0,把它的值设置1
if (compareAndSetState(0, 1))
// 设置当前线程获得锁
setExclusiveOwnerThread(Thread.currentThread());
else
// 尝试去获得锁
acquire(1);
}
public final void acquire(int arg) {
// tryAcquire尝试去获得锁
if (!tryAcquire(arg) &&
//
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
进入nofairTryAcquire
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// state等于0就表示锁没有被使用
if (compareAndSetState(0, acquires)) {
// 获取锁成功,返回true
setExclusiveOwnerThread(current);
return true;
}
}
// 如果独占线程等于当前线程,处理重入锁
else if (current == getExclusiveOwnerThread()) {
// 对state+1
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
// 并设置state的值
setState(nextc);
return true;
}
// 否则尝试获得锁失败
return false;
}
执行addWaiter
private Node addWaiter(Node mode) {
// node有当前线程的对象,下一个等待的线程为空
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
// 第一个进来的时候tail为空
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
执行enq方法
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
// 初始化head等于空Node对象
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
// 如果t等于tail,就node赋值个tail
if (compareAndSetTail(t, node)) {
t.next = node;
// 赋值成功,返回node的前一个节点
return t;
}
}
}
}
现在变化成
进入acquireQueued
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
// 获取node的上一个节点
final Node p = node.predecessor();
// 没有其他线程竞争锁了
if (p == head && tryAcquire(arg)) {
// 设置当前的节点为head
setHead(node);
p.next = null; // help GC
failed = false;
// 返回false
return interrupted;
}
// 阻塞线程
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
进入shouldParkAfterFailedAcquire
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;
}
进入parkAndCheckInterrupt
private final boolean parkAndCheckInterrupt() {
// 底层用的阻塞线程的方法,重点
LockSupport.park(this);
return Thread.interrupted();
}
调用unlock方法
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
进入tryRelease
protected final boolean tryRelease(int releases) {
// 减一,释放重入的锁
int c = getState() - releases;
// 必须获得锁的线程
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// 重入锁释放完了才返回true
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
进入unparkSuccessor,重点
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);
/*
* 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;
}
// 获得head的下一node,唤醒这个node存储的thread
if (s != null)
LockSupport.unpark(s.thread);
}