使主线程高效地等待直到所有工作线程都执行完成,因此可以统计所消耗的时间。
/** * TestHarness * * Using CountDownLatch for starting and stopping threads in timing tests * * @author Brian Goetz and Tim Peierls */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; }}
startGate.countDown() ,准备工作完成后,使所有工作线程开始工作;
endGate.await() 使所有工作线程都执行完后,执行下面的代码。