java - ThreadMXBean.getThreadCpuTime 返回 0
问题描述
由于时间限制,我不得不对 Java 线程进行一些速成课程,如果这个问题看起来很无知,请原谅我。主要思想是我试图为 DoubleHash 的搜索功能获取 CPU 时间,但由于某种原因,即使线程似乎可以正常运行和终止,我也将 CPU 时间设为零。任何帮助表示赞赏。
双哈希线程.java
import doubleHash.DoubleHash;
public class DoubleHashThread extends Thread
{
public String[] hashTable= new String[DoubleHash.TABLE_SIZE];
public String studentId;
public DoubleHashThread(String s)
{
this.setName(s);
}
//OVERRIDE RUN TO RUN SEARCH FUNCTION
@Override
public void run()
{
int a = 0;
for(int i = 0; i < 1; i++)
{
a++;
DoubleHash.searchTable(hashTable, studentId);
DoubleHash.getCpuTime(this);
System.out.println("inside thread, is alive: " + this.isAlive());
}
return;
}
主要片段
//CREATE A THREAD AND ADD TO LIST
threadList.add(new DoubleHashThread("Double Hash Thread"));
threadList.get(0).setDaemon(true);
//UPDATE THREAD HASH TABLE
threadList.get(0).hashTable = hashTable;
//GET USER INPUT
sc.nextLine(); //clear buffer
System.out.println("Please Enter the Student ID ");
data=sc.nextLine();
//UPDATE WANTED STUDENT ID
threadList.get(0).studentId = data;
//START THREAD EXECUTION
threadList.get(0).start();
//TERMINATE THREAD AND REMOVE FROM LIST
try
{
threadList.get(0).join();
threadList.remove(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
获取CPU时间
public static long getCpuTime(DoubleHashThread dt)
{
ThreadMXBean bean = ManagementFactory.getThreadMXBean(); //GET THREAD BEAN
long cpuTime = -1000;
if (bean.isThreadCpuTimeSupported())
{
System.out.println("in get cpu method, status: " + dt.getState());
System.out.println("CPU time for ID: " + dt.getId() +
" THREAD NAME: " + dt.getName() + " is " + bean.getThreadCpuTime(dt.getId()));
cpuTime = bean.getThreadCpuTime(dt.getId());
}
return cpuTime;
}
更新 1 有趣的是,它返回给我的第一个线程 CPU 时间不是 0,但后续的总是 0。
解决方案
推荐阅读
- javascript - javascript 错误记录器正在传递一个我想记录详细信息的重试函数
- java - Java socket.io 等待回调
- javascript - 汇总:未捕获的 ReferenceError:未定义 async_hooks
- firebase - 部署 firebase 应用程序时出错:命令需要范围
- python - 如何从数据框中排除特定行?
- angular - IONIC 5 找不到类型为“object”的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays
- erlang - 未调用 Ejabberd 中的自定义模块
- docker - 码头工人错误!bash:docker.exe:找不到命令
- mysql - 如何在 MySQL 的数据透视表上更好地使用逻辑门
- python - 基于日志数据列有效地重复熊猫数据帧行