閉鎖(CountDownLacth)使用及原理分析

2021-10-23 07:29:01 字數 1759 閱讀 6319

1. countdowmlatch是什麼?

countdownlatch也叫閉鎖,可以使得乙個/多個執行緒等待閉鎖開啟後執行;

2. 應用場景示例

public class countdownlatchtest 

try catch (exception e)

system.out.println("主線程在子執行緒全部結束後結束");

}static class subthread implements runnable

@override

public void run() catch (exception e) finally }}

}

3. 原理分析countdownlatch中定義了乙個繼承了aqs的靜態內部類sync,操作sync的count就是操作aqs的state;

當呼叫countdown的時候,執行的是aqs的releaseshared(int arg)->doreleaseshared()->compareandswapint方法讓state減一;若state為0了,則喚醒await中掛起的主線程(此時隊頭的執行緒正好是主線程);

countdownlatch:

public void countdown()

aqs:

public final boolean releaseshared(int arg)

return false;

}private void doreleaseshared()

else if (ws == 0 &&

!compareandsetwaitstatus(h, 0, node.propagate))

continue; // loop on failed cas

}if (h == head) // loop if head changed

break;}}

當呼叫await的時候,執行的是aqs的acquiresharedinterruptibly>doacquiresharedinterruptibly嘗試獲得鎖,若此時state!=0,表示主線程不可執行,加入到等待佇列中,等待被喚醒。

countdownletch:

public void await() throws interruptedexception

aqs:

public final void acquiresharedinterruptibly(int arg)

throws interruptedexception

private void doacquiresharedinterruptibly(int arg)

throws interruptedexception

}if (shouldparkafte***iledacquire(p, node) &&

parkandcheckinterrupt())

throw new interruptedexception();

}} finally }​

閉鎖 CountDownLatch 原始碼

成員sync 所含方法 await await long,timeunit countdown,getcount 內部靜態類sync extends abstractqueuedsynchronizer 1 兩個公開方法,await和countdown,不存在獲取資源的操作,在初始化的時候已經設定s...

閉鎖CountDownLatch的簡單實現

public class testcountdownlatch catch exception e finally t.start system.out.println c start.countdown 到達此處時,由於finally中已經呼叫了三次countdown 方法,計數已經是0了 所以此...

mysql 關閉鎖 Mysql 鎖

鎖分類 行鎖間隙鎖 表鎖行鎖 鎖原理是基於索引的,如果不命中索引就會公升級為表鎖,注意innodb儲存引擎 1 查自動提交是否關閉 命令列開啟兩個視窗,視窗1關閉自動提交 show variables like autocommit 關閉自動提交 set autocommit 0 select fr...