ReentrantLock lock = new ReentrantLock();
lock.lock();
lock.unlock();
lock();如果获取成功,则设置独占线程。获取结束。
final void lock() {
//通过cas获取锁成功
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
//获取失败
acquire(1);
}
acquire(); 如果获取失败,则再次尝试获取。
public final void acquire(int arg) {
if (!tryAcquire(arg) && //再次尝试获取锁
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//如果获取锁失败,并且加入阻塞队列成功。线程挂起。
selfInterrupt();
}
tryAcquire()--->nonfairTryAcquire(); 如果再次获取成功,则结束。
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
//获取锁的状态
int c = getState();
//如果==0,说明没有线程持有锁,将再次尝试获取锁
if (c == 0) {
//再次尝试
if (compareAndSetState(0, acquires)) {
//获取成功,设置独有线程
setExclusiveOwnerThread(current);
return true;
}
}
//如果是重入锁,设置state.
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;
}
addWaiter(); 再次获取失败,则加入等待队列。并挂起。
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
//第一次,tail为 null 跳过
//第二次,tail不为null,将node加入到链表中。(阻塞队列)
if (pred != null) {
//node的上一个指向tail
node.prev = pred;
if (compareAndSetTail(pred, node)) {
//tail的下一个指向node。
pred.next = node;
return node;
}
}
//初始化head和tail,并将node节点加入到链表(阻塞队列)中。
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
//自旋,第一次t为null
if (t == null) { // Must initialize
//设置head节点
if (compareAndSetHead(new Node()))
//head和tail为同一节点。
tail = head;
} else {
//第二次。node的上一个指向tail。
node.prev = t;
//将node设置为tail
if (compareAndSetTail(t, node)) {
//t的next指向node。即node变成了尾节点。
t.next = node;
return t;
}
}
}
}
acquireQueued(Node node);返回的是tail节点,处理tail节点。
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
//倒叙遍历阻塞队列(链表)
final Node p = node.predecessor();
//如果node的上一个节点就是head节点,则再次尝试获取锁。
if (p == head && tryAcquire(arg)) {
//如果获取成功,则将head设置为node
setHead(node);
//下一个指向null。即tail为null。
p.next = null; // help GC
failed = false;
return interrupted;
}
//获取失败,则挂起在这里。
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}