import java.util.concurrent.CountDownLatch;
public class TestHarness {
public static void main(String[] args) throws InterruptedException {
MyTask task = new MyTask();
System.out.println(timeTasks(2, task));
}
public static 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 e) {
// TODO: handle exception
}
}
};
t.start();
}
long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
return end - start;
}
}
class MyTask implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread());
}
}
一个简单的闭锁例子
最新推荐文章于 2021-08-24 17:20:57 发布