import java.util.concurrent.CountDownLatch;
publicclassTestHarness {publiclongtimetasks(int nThreads, final Runnable task) throws InterruptedException {
// init start from 1.final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i=0;i< nThreads;i++){
Thread t = new Thread(){
publicvoidrun(){
try{
startGate.await();//wait the startgate count down to zero, then run.try{
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored){ }
}
};
t.start();
}
long start = System.nanoTime(); //单位纳秒
startGate.countDown();
endGate.await();//wait the endGate count down to zero, then run.long end = System.nanoTime();
return end - start;
}
}
我写的测试类
publicclass Solution {
publicstaticvoidmain(String[] args) throws InterruptedException {
final Thread tt = new Thread(){
@Override
publicvoidrun() {
System.out.println("Thread Id: " + this.getId()); //具体的方法,比如DOTA2中点击准备就绪的按键
}
};
TestHarness bisuo = new TestHarness();
long threadtime = bisuo.timetasks(100,tt);
double ans = (double)threadtime / 1000000000;
System.out.println("Thread time:" +ans + "s");
}
}