java - `监控java中每个线程的cpu使用情况?

标签 java multithreading cpu-usage

我想问是否有一些简单的方法来确定java 中每个线程的cpu 使用率。谢谢

最佳答案

我相信 JConsole ( archived link ) 确实通过插件提供了这种信息

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);
            }
        }

关于java - `监控java中每个线程的cpu使用情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/755899/

相关文章:

java - 如何使用 Ant 执行 JUnit 测试的子集?

objective-c - 如何使用[performSelector : onThread: withObject: waitUntilDone:]?

java - 使用 OSHI lib 计算进程(作业)占用的内存

c++ - 将线程分配给特定的 CPU 内核

java - 属性 "Year"的冲突 setter 定义 (Springfox-Swagger2)

java - 持久对象异常 : detached entity passed to persist - Got this exception when run method 2nd time

java - 从 linkedin api 获取技能?

c# - 更新在另一个线程中创建的控件?

multithreading - 如何知道线程是否在Perl中使用die

linux - 进程完成后的 CPU 时间