Java obtains the CPU and memory usage of Linux by calling the TOP command.

Source: Internet
Author: User

In Java programming, you want to know the CPU usage to determine whether to load the task. First, search by google. In Windows, you can use JNI to Use API functions.
GetProcessCPUTime (), and someone gives the source code. Linux does not seem to have any source code, so I decided to write it myself. After practice, I finally succeeded. Now I will
Post the code and share it with you.

The idea is as follows: in Linux, you can use the top command to view the CPU usage and memory usage of processes. The system command "top" in the exec () method of the Runtime class gets the output of "top, to obtain the CPU and memory usage. A little change to this program can also get the memory usage.

 

Package com. hmw. test;

Import java. io. BufferedReader;
Import java. io. InputStreamReader;

/**
* @ Author wanlh
* @ Version 1.0
*/
Public class CpuUsage {
Public double getCpuUsage () throws Exception {
Double cpuUsed = 0;
Runtime rt = Runtime. getRuntime ();
Process p = rt.exe c ("top-B-n 1"); // call the system's "top" command
BufferedReader in = null;
Try {
In = new BufferedReader (new InputStreamReader (p. getInputStream ()));
String STR = NULL;
String [] strarray = NULL;
While (STR = in. Readline ())! = NULL ){
Int m = 0;
If (Str. indexof ("R ")! =-1 & Str. indexof ("TOP") =-1) {// only the running process is analyzed, except for the top process itself
Strarray = Str. Split ("");
For (string TMP: strarray ){
If (TMP. Trim (). Length () = 0)
Continue;
If (++ M = 9) {// percentage of CPU usage in the 9th column (RedHat 9)
Cpuused + = double. parsedouble (TMP );
}
}
}
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
In. Close ();
}
Return cpuused;
}

Public static void main (string [] ARGs) throws exception {
Cpuusage CPU = new cpuusage ();
System. out. println ("cpu used:" + cpu. getCpuUsage () + "% ");
}
}

 

 

Source: http://www.itpub.net/archiver/tid-859283.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.