就像主题所说的那样,它是否包括在 BLOCKED 和 WAITING 等状态中花费的时间,或者这只是 RUNNABLE ?文档只是说“cpu time”,这有点含糊......
问问题
4990 次
3 回答
3
ThreadMXBean.getThreadCpuTime() 仅包括在 RUNNABLE 状态下花费的时间,但请注意,计算方式取决于平台。
这是一个程序,它显示 getThreadCpuTime() 仅涵盖线程实际执行某些操作的时间:
import java.lang.management.*;
public class Test implements Runnable {
public static void main(String[] args)
throws Exception {
long time = System.nanoTime();
Test test = new Test();
synchronized (test) {
new Thread(test).start();
while (test.cpu == -1) {
test.wait();
}
}
System.out.println("time: " + (System.nanoTime() - time));
System.out.println("cpu: " + test.cpu);
}
private long cpu = -1;
public synchronized void run() {
try {
ThreadMXBean thread = ManagementFactory.getThreadMXBean();
long cpu = thread.getCurrentThreadCpuTime();
Thread.sleep(300);
long time = System.nanoTime();
while (System.nanoTime() - time < 700000000);
this.cpu = thread.getCurrentThreadCpuTime() - cpu;
}
catch (InterruptedException _) {}
finally {
notify();
}
}
}
于 2012-06-10T18:56:15.600 回答
1
是的,这只是RUNNABLE
,您可以通过ThreadInfo使用以下方法进一步统计在其他状态中花费的时间:
TIMED_WAITING
和之间没有进一步WAITING
的区别getWaitedTime()
。
于 2012-07-08T17:00:27.343 回答
0
仅可运行。就是这样,否则就没用了。
于 2012-06-10T18:39:03.760 回答