1

由于时间限制,我不得不对 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。

4

0 回答 0