2009-04-16 134 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。

相關問題