都說理解了AQS就理解了鎖的機制 那我就一個一個方法來吧~~~
這次講講juc裏面的CountDownLatch
CountDownLatch 結構
其實CountDownLatch裏面還真沒那麼幾個屬性方法,一個內部類Sync繼承AQS 加上了6個方法組成。
CountDownLatch 運行方式
CountDownLatch的使用就像火箭發射,倒數到0就進行發射。
- 上圖的main爲主線程,運行到某個時間點時調用await()方法暫停,
- 並有4個線程開始執行 每個線程執行完都會調用countDown()方法進行“倒計時”
- 當4個都完成時,main線程繼續運行。
CountDownLatch 內部詳細分析
CountDown沒有空構造方法 唯一個構造方法是
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
先判斷參數是否異常,然後調用了是創建了一個Sync的對象。
// CountDownLatch.Sync
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState(); // 獲取當前可用值
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();// 獲取當前state
if (c == 0)
return false; // 如果爲0已經釋放
int nextc = c-1; // 否則對當前state - 1
if (compareAndSetState(c, nextc))
return nextc == 0; // 利用CAS操作處理多線程併發
}
}
}
private final Sync sync;
其中就很明顯看出CountDownLatch底層是依照AQS來實現的了,
使用AQS中state屬性。
在我們await時 調用了acquireSharedInterruptibly(1)
// CountDownLatch --> await()
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
這個是AQS裏實現的方法
// AQS --> acquireSharedInterruptibly()
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted()) // 線程中斷拋出異常
throw new InterruptedException();
if (tryAcquireShared(arg) < 0) // 申請鎖
doAcquireSharedInterruptibly(arg);
}
// CountDownLatch -->Sync.tryAcquireShared()
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
先判斷了是否state爲0 不爲0說明還沒有釋放完繼續執行下面方法
那爲什麼爲0的情況什麼也沒操作呢?先接着往下看 接下去就到了更深的AQS層面了。
// AQS --> doAcquireSharedInterruptibly(arg);
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED); // 作爲共享模式加入
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor(); // 獲得node隊列頭結點
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) { // 根據上文CountDownLatch的方法 1 表示state=0 |-1表示state>0
// 設置頭結點並繼續喚醒
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
// 由於多線程情況 如果被別的線程喚醒了等 所以如果喚醒失敗判斷是否有必要結束
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node); // 失敗時候進行後續處理
}
}
// AQS --> addWaiter()
private Node addWaiter(Node mode) {
// 以共享模式把當前線程加入隊列的尾部
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail; // 獲得隊列尾部節點
if (pred != null) {
node.prev = pred; // 將本節點前元素只向尾部
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node); // 在多線程環境下 如果cas失敗採用該方法加入 但速度肯定還是cas快
return node;
}
看了上面的代碼分析是否頭暈眼花,await()
之後大致流程如下
- 判斷線程被打斷 -->拋異常
- 嘗試獲取鎖 失敗後以共享模式加入等待隊列中 共享鎖也就是獲取了之後別人也可以獲取的鎖
- 繼續獲取鎖 並從頭部開始喚醒線程 因爲是共享模式獲得鎖後會一直喚醒
- 如果喚醒成功則返回
其中最主要的喚醒依據就是state
字段
在CountDownLatch的countdown方法中對其進行修改
//CountDownLatch --> countDown();
public void countDown() {
sync.releaseShared(1);
}
//AQS --> releaseShared()
public final boolean releaseShared(int arg) {
// 獲取鎖如果獲取成功則對線程進行喚醒 這裏的arg爲1
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
//CountDownLatch --> Sync.tryReleaseShared(int releases)
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();// 獲取當前state
if (c == 0)
return false; // 如果爲0已經釋放
int nextc = c-1; // 否則對當前state - 1
if (compareAndSetState(c, nextc))
return nextc == 0; // 利用CAS操作處理多線程併發
}
}
// 在獲取到鎖後 也就是當前線程把state減到0後
// CountDownLatch --> doReleaseShared()
private void doReleaseShared() {
for (;;) {
//喚醒操作由頭結點開始,注意這裏的頭節點已經是上面新設置的頭結點了
//其實就是喚醒上面新獲取到共享鎖的節點的後繼節點
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
//表示後繼節點需要被喚醒
if (ws == Node.SIGNAL) {
//這裏需要控制併發,因爲入口有setHeadAndPropagate跟release兩個,避免兩次unpark
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue;
//執行喚醒操作
unparkSuccessor(h);
}
//如果後繼節點暫時不需要喚醒,則把當前節點狀態設置爲PROPAGATE確保以後可以傳遞下去
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue;
}
//如果頭結點沒有發生變化,表示設置完成,退出循環
//如果頭結點發生變化,比如說其他線程獲取到了鎖,爲了使自己的喚醒動作可以傳遞,必須進行重試
if (h == head)
break;
}
}
以上就是CountDownLatch的核心下面是簡單的用例執行
CountDownLatch demo
class Resource implements Runnable{
private CountDownLatch countDownLatch;
public Resource(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+"\t 倒計時"+countDownLatch.getCount());
}
}
public class ValidKo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
new Thread(new Resource(countDownLatch),"線程"+i).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t 倒計時結束 發射");
}
}
以上就是所以內容了 後續有補充再繼續改動~~~
感謝閱讀~~~