'在java中监视每个线程的CPU使用率?

2022-09-01 07:42:47

我想问一下,是否有一些简单的方法来确定中的每个线程。谢谢cpu usagejava


答案 1

我相信JConsole存档链接)确实通过插件提供了这种信息

JConsole Thread CPU usage, after blogs.oracle.com/lmalventosa/resource/thread_cpu_usage.jpg

它使用ThreadMXBean getThreadCpuTime()函数。

大致内容如下:

        long upTime = runtimeProxy.getUptime();
        List<Long> threadCpuTime = new ArrayList<Long>();
        for (int i = 0; i < threadIds.size(); i++) {
            long threadId = threadIds.get(i);
            if (threadId != -1) {
                threadCpuTime.add(threadProxy.getThreadCpuTime(threadId));
            } else {
                threadCpuTime.add(0L);
            }
        }
        int nCPUs = osProxy.getAvailableProcessors();
        List<Float> cpuUsageList = new ArrayList<Float>();
        if (prevUpTime > 0L && upTime > prevUpTime) {
            // elapsedTime is in ms
            long elapsedTime = upTime - prevUpTime;
            for (int i = 0; i < threadIds.size(); i++) {
                // elapsedCpu is in ns
                long elapsedCpu = threadCpuTime.get(i) - prevThreadCpuTime.get(i);
                // cpuUsage could go higher than 100% because elapsedTime
                // and elapsedCpu are not fetched simultaneously. Limit to
                // 99% to avoid Chart showing a scale from 0% to 200%.
                float cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 1000000F * nCPUs));
                cpuUsageList.add(cpuUsage);
            }
        }

答案 2

通过使用java.lang.management.ThreadMXBean。如何获取 ThreadMXBean:

 ThreadMXBean tmxb = ManagementFactory.getThreadMXBean();

然后,您可以使用以下命令查询特定线程消耗了多少:

 long cpuTime = tmxb.getThreadCpuTime(aThreadID);

希望它有帮助。