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类似于一扇门,当这扇门可能有一个或多个钥匙孔,只有当满足门上的所需的所有钥匙之后,门才会打开,所有在门前等待的线程才可以同时进入门中继续操作。