首先是获取当前Java运行的Java进程ID,这个是网上常见的,也就是Java程序自身将进程ID打印出来:
package com.test;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
public class Target {
public static void main(String[] args) throws InterruptedException {
System.out.println(getProcessID());
while(true) {
Thread.sleep(10000);
}
}
public static final int getProcessID() {
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
System.out.println(runtimeMXBean.getName());
return Integer.valueOf(runtimeMXBean.getName().split("@")[0])
.intValue();
}
}
运行结果:
2896@PC-20150603VRPL
2896
获取所有正在运行着的Java进程
package com.test;
import java.util.HashSet;
import java.util.Set;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
public class ProcessID {
public static void main(String[] args) throws Exception {
// 获取监控主机
MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
// 取得所有在活动的虚拟机集合
Set<?> vmlist = new HashSet<Object>(local.activeVms());
// 遍历集合,输出PID和进程名
for(Object process : vmlist) {
MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
// 获取类名
String processname = MonitoredVmUtil.mainClass(vm, true);
System.out.println(process + " ------> " + processname);
}
}
}
MonitoredHost等类位于${JAVA_HOME}/lib/tools.jar
运行结果:
2752 ------>
5172 ------> com.test.Target
5308 ------> com.test.ProcessID
下面是一个可以直接根据类找到对应Java进程ID的方法:
package com.test;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
public class ProcessID {
public static void main(String[] args) throws Exception {
int pid = getProcess(Target.class);
System.out.println("PID: "+pid);
}
public static int getProcess(Class<?> cls) throws MonitorException, URISyntaxException {
if(cls == null) {
return -1;
}
// 获取监控主机
MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
// 取得所有在活动的虚拟机集合
Set<?> vmlist = new HashSet<Object>(local.activeVms());
// 遍历集合,输出PID和进程名
for(Object process : vmlist) {
MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
// 获取类名
String processname = MonitoredVmUtil.mainClass(vm, true);
if(cls.getName().equals(processname)) {
return ((Integer)process).intValue();
}
}
return -1;
}
}