多线程Java:如何在多线程程序中测试细粒度
在Java中,我有简单的多线程代码:
public class ThreadedAlgo {
public static final int threadsCount = 3;
public static void main(String[] args) {
// start timer prior computation
time = System.currentTimeMillis();
// create threads
Thread[] threads = new Thread[threadsCount];
class ToDo implements Runnable {
public void run() { ... }
}
// create job objects
for (int i = 0; i < threadsCount; i++) {
ToDo job = new ToDo();
threads[i] = new Thread(job);
}
// start threads
for (int i = 0; i < threadsCount; i++) {
threads[i].start();
}
// wait for threads above to finish
for (int i = 0; i < threadsCount; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// display time after computation
System.out.println("Execution time: " + (System.currentTimeMillis() - time));
}
}
它工作得很好,现在我想运行2到3个线程,并计算每个线程的计算时间。然后我会比较时间:通过t1
和t2
来记录它们,如果|t1 - t2| < small epsilon
,我会说我的算法在某些给定条件下执行的粒度很细,也就是说线程花费的时间相对相同
如何测量线的时间
# 1 楼答案
在线程(作业)方法的开头和结尾使用}
System.nanoTime()
来计算每次调用花费的总时间。在您的情况下,所有线程都将以相同的(默认)优先级执行,其中时间片的分配应该相当公平。如果你的线程是互锁的,出于同样的原因使用“公平锁”;e、 g.^{