package five;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import common.Utils;
public class CountThreadRunTime {
private static final int threadNumber = 3;
private static CountDownLatch startLatch = new CountDownLatch(1);
private static CountDownLatch endLatch = new CountDownLatch(threadNumber);
public static void countRunTime() {
for (int i = 0; i < threadNumber; i++) {
Thread thread = new Thread() {
@Override
public void run() {
try {
startLatch.await();
for (int i = 0; i < 10; i++)
Utils.sleep(TimeUnit.NANOSECONDS, 1);
} catch (InterruptedException e) {
} finally {
endLatch.countDown();
}
}
};
thread.start();
}
long start = System.nanoTime();
startLatch.countDown();// 开始让所有线程执行
try {
endLatch.await();// 让主线程阻塞,直到其他线程运行停止
} catch (InterruptedException e) {
}
long end = System.nanoTime();
System.out.println((end - start) * 1.0 / (1000L * 1000 * 1000) + "s");
}
public static void main(String args[]) {
countRunTime();
}
}
计算线程运行时间
最新推荐文章于 2024-06-30 03:36:23 发布