欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用RuntimeMXBean获取PID

程序员文章站 2022-05-26 10:25:37
...

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];
	}
}


控制台输出信息如下:
使用RuntimeMXBean获取PID
            
    
    博客分类: Java PIDjava 

在任务管理器中查找获取的PID。

使用RuntimeMXBean获取PID
            
    
    博客分类: Java PIDjava 

  • 使用RuntimeMXBean获取PID
            
    
    博客分类: Java PIDjava 
  • 大小: 68.2 KB
  • 使用RuntimeMXBean获取PID
            
    
    博客分类: Java PIDjava 
  • 大小: 68.5 KB
相关标签: PID java