java.lang.management.RuntimeMXBean是Java 虚拟机的运行时系统的管理接口。使用它可以获取正在运行的 Java 虚拟机等信息,包括获取PID。
以下就是一个获取PID的例子:
控制台输出信息如下:
[img]http://dl2.iteye.com/upload/attachment/0088/3245/607205c6-682b-3f87-a93c-e29e32bc31a3.jpg[/img]
在任务管理器中查找获取的PID。
[img]http://dl2.iteye.com/upload/attachment/0088/3243/36730e62-fb34-3856-8e64-f62350debccd.jpg[/img]
以下就是一个获取PID的例子:
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.logging.Logger;
public class RuntimeMXBeanUtil {
private static final Logger logger = MyLoggerUtil.setLoggerHanlder(Logger.getLogger("RuntimeMXBeanUtil"));
private static final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
public static void main(String[] args) {
logger.info("BootClassPart-->\n"+runtimeMXBean.getBootClassPath());
//logger.info("ManagerSpecVersion is "+runtimeMXBean.getManagementSpecVersion());
//logger.info("ClassPath is "+runtimeMXBean.getClassPath());
//logger.info("Library path is "+runtimeMXBean.getLibraryPath());
/**
* Populate the process ID
*/
logger.info("The PID is "+populateProcessID());
logger.info("Spec Name is "+runtimeMXBean.getSpecName());
logger.info("Spec Vendor is "+runtimeMXBean.getSpecVendor());
//logger.info("Spec Version is "+runtimeMXBean.getSpecVersion());
//logger.info("Start Time is "+runtimeMXBean.getStartTime());
//logger.info("Start Time is "+runtimeMXBean.getStartTime());
//logger.info("Update Time is "+runtimeMXBean.getUptime());
logger.info("VM Name is "+runtimeMXBean.getVmName());
logger.info("VM Vendor is "+runtimeMXBean.getVmVendor());
logger.info("VM Version is "+runtimeMXBean.getVmVersion());
/**
* Get System Properties
*/
logger.info("System Properties--> "+runtimeMXBean.getSystemProperties());
//logger.info("Is boot class path supported? "+runtimeMXBean.isBootClassPathSupported());
//System.getProperties();
//what is the difference between ManagementFactory.getRuntimeMXBean().getSystemProperties() and System.getProperties() ?
//The difference is you can use RuntimeMXBean from a remote JVM to obtain its system properties.
//System.out.println(runtimeMXBean.getSystemProperties().size() == System.getProperties().size());
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null,
"The PID is " +populateProcessID() , null, javax.swing.JOptionPane.DEFAULT_OPTION);
}
private static String populateProcessID()
{
/*
* runtimeMXBean.getName()取得的值包括两个部分:PID和hostname,两者用@连接。
*/
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
return runtimeMXBean.getName().split("@")[0];
}
}
控制台输出信息如下:
[img]http://dl2.iteye.com/upload/attachment/0088/3245/607205c6-682b-3f87-a93c-e29e32bc31a3.jpg[/img]
在任务管理器中查找获取的PID。
[img]http://dl2.iteye.com/upload/attachment/0088/3243/36730e62-fb34-3856-8e64-f62350debccd.jpg[/img]