使主线程高效地等待直到所有工作线程都执行完成,因此可以统计所消耗的时间。
/**
* TestHarness
* <p/>
* 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() 使所有工作线程都执行完后,执行下面的代码。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。