您的位置:首页 > 编程语言 > Java开发

一个简单的闭锁例子

2014-05-27 23:00 204 查看
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());

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java thread