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