只談?wù)劊蝗采w
簡單介紹重入鎖
ReentrantLock為并發(fā)包多數(shù)的類提供底層應(yīng)用。重要性不言而喻,重入鎖實現(xiàn)的基石就是AbstractQueuedSynchronizer。所以把AbstractQueuedSynchronizer研究透,就可以摸清重入鎖是如何實現(xiàn)的。
ReentrantLock的Sync內(nèi)部類繼承了AbstractQueuedSynchronizer,ReentrantLock的非公平鎖與公平鎖都繼承了Sync
- 公平鎖
先判斷如果當前線程之前的節(jié)點沒有排隊的線程(hasQueuedPredecessors, 就是要乖乖的按順序排隊),則當前線程可以獲取鎖,否則插入隊尾等待喚醒。 - 非公平鎖
上來就先搶占鎖,如果搶占不到再去嘗試獲取鎖(nonfairTryAcquire,各種搶占誰搶到算誰的),如果獲取不到,則插入隊尾等待喚醒。
拿公平鎖舉例
通過一段代碼,闡述下,ReentrantLock的公平鎖是如果做到線程同步的。
public void lockT() {
ReentrantLock lock = new ReentrantLock(true); // 公平鎖
for (int i = 0; i < 5; i++) { // 模擬5個線程執(zhí)行
singleThreadPool.execute(() -> {
lock.lock(); // 上鎖
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock(); // 解鎖
});
}
singleThreadPool.shutdown();
}
- 等待隊列節(jié)點類
static final class Node {
// 共享模式節(jié)點
static final Node SHARED = new Node();
// 獨占模式節(jié)點
static final Node EXCLUSIVE = null;
// 表示線程已被取消
static final int CANCELLED = 1;
// 表示后續(xù)線程需要喚醒(線程可被喚醒的標識)
static final int SIGNAL = -1;
// 表示線程正在等待條件
static final int CONDITION = -2;
// 傳播等待狀態(tài),表示無條件傳播(執(zhí)行)
static final int PROPAGATE = -3;
// 對于正常同步節(jié)點,此字段初始化為0,對于條件節(jié)點初始化值應(yīng)該是 CONDITION -2。waitStatus 對應(yīng)以上狀態(tài)值(CANCELLED、SIGNAL 、CONDITION、PROPAGATE)。
volatile int waitStatus;
// 當前節(jié)點的前一個節(jié)點
volatile Node prev;
// 當前節(jié)點的后一個節(jié)點
volatile Node next;
// 正在排隊的線程節(jié)點。在構(gòu)造時初始化,并在使用后清除
volatile Thread thread;
// 鏈接下一個正在等待條件的節(jié)點,或者指定值為 SHARED 的節(jié)點。因為條件隊列只有當持有獨占模式下時才能被訪問,我們只需要一個簡單的鏈隊列去保持正在等待條件的節(jié)點。他們在這個隊列中轉(zhuǎn)換成重新獲?。╮e-acquire)節(jié)點。并且條件只能為獨占,所以我們使用這個屬性來保存特殊的值,表示為一個共享模式
Node nextWaiter;
// 如果節(jié)點在共享模式下等待,則返回 true
final boolean isShared() {
return nextWaiter == SHARED;
}
// 返回前一個節(jié)點,或者如果為空拋出空指針異常。當前一個不為空時可以使用。
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() { // Used to establish initial head or SHARED marker
}
Node(Thread thread, Node mode) { // Used by addWaiter 使用的等待模式
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition 使用的等待狀態(tài)
this.waitStatus = waitStatus;
this.thread = thread;
}
}
- 上鎖
public void lock() {
sync.lock();
}
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
// 嘗試獲取鎖失敗,并且成功加入等待隊列。線程自己中斷。
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
- 首先嘗試獲取鎖
tryAcquire
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread(); // 獲取當前線程
int c = getState(); // 同步狀態(tài), 狀態(tài)為0時表示鎖空閑,當前線程可以獲取鎖
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) { // 表示當前線程之前的線程是否有排隊的,如果有跳出 if,沒有就走原子更新狀態(tài)從0變1.表示該鎖已被占用
setExclusiveOwnerThread(current); // 設(shè)置獨占線程所有者為當前線程
return true;
}
}
else if (current == getExclusiveOwnerThread()) { // cpu 時間片,鎖重入
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
// 每次公平鎖都要進行這個判斷。如果在當前線程之前有一個排隊的線程返回true,如果當前線程在隊列的頭或者隊列為空返回false
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread()); // 首尾不相等 并且 s 為隊頭的下一個節(jié)點為空或者 s 的線程不等于當前線程
}
- 獲取鎖失敗后,把當前線程組裝成新的節(jié)點加入到等待隊列中。
private Node addWaiter(Node mode) {
// 要添加等待隊列的線程節(jié)點
Node node = new Node(Thread.currentThread(), mode);
// 嘗試把新的節(jié)點插入在隊列的尾部
// pred 指向隊尾
Node pred = tail;
// 如果隊尾有值,則進行 cas 隊尾替換,并移動上一個隊尾的指針
if (pred != null) {
// 不為空時,新節(jié)點的前一個指向隊尾,隊尾的后一個節(jié)點指向新節(jié)點
node.prev = pred;
// 隊尾原子替換
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
// 如果隊尾為空或者隊尾原子替換失敗,則走 enq 方法
enq(node);
// 返回新節(jié)點
return node;
}
private Node enq(final Node node) { // final 類型的節(jié)點
// 自旋
for (;;) {
// t 指向隊尾的引用
Node t = tail;
// 如果 t 為空必須要初始化一個空的隊頭
if (t == null) {
// 成功初始化一個空的隊頭
if (compareAndSetHead(new Node()))
// 隊尾指向空隊頭的引用
tail = head;
} else { // 如果 t 不為空,將節(jié)點插入隊尾
// 參數(shù)節(jié)點的前一個值指向 t
node.prev = t;
// 進行尾部的原子替換,把 t 替換成 node
if (compareAndSetTail(t, node)) {
// 成功后,t 的下一個節(jié)點指向參數(shù) node
t.next = node;
// 返回前一個節(jié)點
return t;
}
}
}
}
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
// 自旋
for (;;) {
// 獲取前一個節(jié)點
final Node p = node.predecessor();
// 如果是隊頭并且重新嘗試獲取鎖成功。 當前節(jié)點是否是重新獲取鎖時的當前線程??答案:是的
if (p == head && tryAcquire(arg)) {
// 隊頭指向隊頭的下一個節(jié)點,使老隊頭出列(設(shè)置新隊頭,老隊頭出列),先進先出
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
// 如果 p 不是隊頭并且獲取鎖失敗后阻塞當前線程,自旋阻塞
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// 獲取鎖失敗之后暫掛(阻塞)該線程
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
// 前節(jié)點的等待狀態(tài)
int ws = pred.waitStatus;
// 前一個節(jié)點的等待狀態(tài)為-1,表示當前線程可以安全的阻塞
if (ws == Node.SIGNAL)
/*
* 前置節(jié)點已經(jīng)是 SIGNAL 狀態(tài),所以當前線程可以被安全阻塞
*/
return true;
if (ws > 0) {
/*
* ws > 0 表示前節(jié)點已經(jīng)被取消,跳過等待狀態(tài)大于0的前節(jié)點并重試
*/
do {
// 跳過狀態(tài)大于0的節(jié)點
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* 等待狀態(tài)必須為0或者為 PROPAGATE。我們需要一個等待狀態(tài)變?yōu)?signal,這時還沒有阻塞。調(diào)用者需要重試,確保它在阻塞前不能獲取鎖
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL); // 把前一個節(jié)點的狀態(tài)由0或者 PROPAGATE 變?yōu)?SIGNAL
}
return false;
}
private final boolean parkAndCheckInterrupt() {
// 掛起(阻塞)當前線程
LockSupport.park(this);
return Thread.interrupted();
}
上鎖總結(jié)
至此關(guān)于重入鎖上鎖部分的源碼分析完畢。其實很簡單,并發(fā)時只有當線程獲取到鎖時,才能進行之后的邏輯操作,如果線程沒有獲取到鎖時,則會被加入雙向鏈表中。公平鎖獲取鎖時每次會通過hasQueuedPredecessors方法判斷當前線程是否為排隊的第一個線程(fifo先進先出)。

大體流程圖
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryAcquire()
hasQueuedPredecessors()
compareAndSetState()
setExclusiveOwnerThread()
getExclusiveOwnerThread()
addWaiter()
compareAndSetTail()
enq()
acquireQueued()
tryAcquire()
shouldParkAfterFailedAcquire()
parkAndCheckInterrupt()
cancelAcquire()
============
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()
setExclusiveOwnerThread()
setState()
unparkSuccessor()
compareAndSetWaitStatus()
unpark()