Try this:
1) To hold all your running processes:
private List<String> processes = new ArrayList<String>();
2) To get all java running processes:
private void getRunningProcesses() throws Exception {
Process process = Runtime.getRuntime().exec("top -b -n1 -c");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null) {
if( line.contains("java") ) processes.add( line );
}
}
3) To get an information line from PID ( getRunningProcesses() first ):
private String getByPid( int pid ) {
for ( String line : processes ) {
if ( line.startsWith( String.valueOf( pid ) ) ) {
return line;
}
}
return "";
}
4) Now you have a line with all "top" information from that PID. Get the CPU %:
private Double getCpuFromProcess( String process ) {
//PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
Double result = 0.0;
String[] items = process.replace(" "," ").replace(" "," ").split(" ");
result = Double.valueOf( items[8].replace(",", ".") );
return result;
}
Done.
EDIT: Don't forget to clear processes list before each call.
EDIT 2: Call
getRunningProcesses()
, then getCpuFromProcess( getByPid( the_pid ) )