使用RuntimeMXBean获取PID

java.lang.management.RuntimeMXBean是Java 虚拟机的运行时系统的管理接口。使用它可以获取正在运行的 Java 虚拟机等信息,包括获取PID。

以下就是一个获取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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值