1. 程式人生 > >使用閉鎖CountDownLatch來實現併發下統計執行時長

使用閉鎖CountDownLatch來實現併發下統計執行時長

1、程式如下:

public class TestHarness {
    public long timeTasks(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++) { Thread t = new Thread() { public void run() { try { startGate.await(); try { task.run(); } finally { endGate.countDown(); } } catch (InterruptedException ignored) {
} } }; t.start(); } long start = System.nanoTime(); startGate.countDown(); endGate.await(); long end = System.nanoTime(); return end - start; } public static void main(String[] args) throws InterruptedException { TestHarness testHarness = new
TestHarness(); long result = testHarness.timeTasks(10, new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getId() + ":"+Thread.currentThread().getName()); } }); System.out.println("時長="+result); } }

2、startGate為起始鎖,初始值為1,在for迴圈建立的執行緒執行run方法之前先呼叫起始鎖的await()方法,讓啟動的執行緒都阻塞在起始鎖位置等待,迴圈執行之後到執行起始鎖的countDown()方法時扣減一之後起始鎖計數器為0時,放開鎖,所有執行緒併發執行任務。

3、endGate為結束鎖,初始值為執行緒數,在起始鎖的await()方法呼叫處阻塞,直到結束鎖的計數器減為0才能繼續往下執行。結束鎖計數器的扣減方法countDown()是在迴圈中建立執行緒的run方法執行完成之後進行的扣減。也就是說,在所有執行緒都完成業務處理之後,結束鎖的計數器才會被扣減為0,利用結束鎖來統計所有執行緒執行完成所使用的時間。

4、閉鎖CountDownLatch類似於一扇門,當這扇門可能有一個或多個鑰匙孔,只有當滿足門上的所需的所有鑰匙之後,門才會開啟,所有在門前等待的執行緒才可以同時進入門中繼續操作。