Multi-Th:同步工具類-閉鎖

閉鎖

閉鎖是一種同步工具類,可以延遲線程的進度直到線程到達終止?fàn)顟B(tài)??梢杂糜诖_保某些活動直到其他活動都完成后繼續(xù)執(zhí)行:

  • 確保某個計算在其需要的所有資源都被初始化之后繼續(xù)執(zhí)行
  • 確保某個服務(wù)在其依賴的所有其他服務(wù)都已經(jīng)啟動之后才啟動。
  • 等待直到某個操作的所有參與者都就緒再繼續(xù)執(zhí)行。

閉鎖就像是一扇門,在閉鎖到達結(jié)束狀態(tài)之前,這扇門一直關(guān)閉的,并且沒有任何線程能夠通過,當(dāng)?shù)竭_結(jié)束狀態(tài)時,這扇門會打開并允許所有的線程通過。(當(dāng)閉鎖到達結(jié)束狀態(tài)后,將不會再改變狀態(tài))


CountDownLatch 是一種靈活的閉鎖實現(xiàn),可以使一個或多個線程等待一組事件發(fā)生。閉鎖狀態(tài)包括一個計數(shù)器,該計數(shù)器被初始化成為一個正數(shù),表示需要等待的事件數(shù)量。countDown 方法遞減計數(shù)器,表示有一個事件已經(jīng)發(fā)生。await 方法等待計數(shù)器到達零,這表示所有需要等待的事件都已經(jīng)發(fā)生。

public class TestHarness {

    public long timeTask(int nThreads, final Runnable task) throws InterruptedException{
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i=0; i<nThreads; i++) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        long startTime = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long endTime = System.nanoTime();
        return endTime - startTime;
    }

    public static void main(String[] args) throws InterruptedException {
        long time = new TestHarness().timeTask(10, new Runnable() {
            public void run() {
                System.out.println("Current Thread : " + Thread.currentThread().getName());
            }
        });

        System.out.println("Task execute time : " + time);
    }
}
結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容