2009-04-16 145 views

回答

17

相信JConsolearchived 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); 
      } 
     } 
+1

请注意,您可能还需要检查您正在运行的JVM中是否启用了CpuTime。 'threadBean_.isThreadCpuTimeEnabled()'将返回布尔值,如果不是'threadBean_.setThreadCpuTimeEnabled(true)',你可以随时设置它。' – Graham 2012-07-06 07:37:22

11

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

ThreadMXBean tmxb = ManagementFactory.getThreadMXBean(); 

然后你就可以查询多少特定线程是通过使用消耗:

long cpuTime = tmxb.getThreadCpuTime(aThreadID); 

希望它能帮助。

1

的确,对象ThreadMXBean提供了您需要的功能(但它可能不会在所有虚拟机上实现)。

在JDK 1.5中,有一个演示程序正在执行您所需的操作。这是在文件夹演示/管理,它被称为JTop.java

不幸的是,它不是在Java6中。也许你可以在谷歌上找到或下载JDK5。

3

Option_1:代码级

在你的业务逻辑代码;在开始时调用start()API和在finally块中调用stop()。这样你可以通过当前正在运行的线程获得执行逻辑的CPU时间。然后记录它。 Reference

class CPUTimer 
{ 
    private long _startTime = 0l; 

    public void start() 
    { 
     _startTime = getCpuTimeInMillis(); 
    } 


    public long stop() 
    { 
     long result = (getCpuTimeInMillis() - _startTime); 
     _startTime = 0l; 
     return result; 
    } 

    public boolean isRunning() 
    { 
     return _startTime != 0l; 
    } 

    /** thread CPU time in milliseconds. */ 
    private long getCpuTimeInMillis() 
    { 
     ThreadMXBean bean = ManagementFactory.getThreadMXBean(); 
     return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime()/1000000: 0L; 
    } 
} 

Option_2:使用插件监控级(不具有jvisualvm支持IBM AIX箱)

如果你认为这是在现在添加代码延迟,那么你可以喜欢用的JConsole插件支持。我跟着this文章。那篇文章下载topthreads罐子和运行./jconsole -pluginpath topthreads-1.1.jar

Option_3:使用TOP(移动H)+监控级JSTACK(Unix机器具有 '希夫+ H' 的支持)

关注this教程, top命令将提供选项以查找最高CPU线程(nid)。在jstack输出文件中检查那个nid。