之前並不知道Java中如何能夠獲取當前進程(也就是包含當前Java程序的JVM所在進程)的進程ID,還以為要通過JNI或者通過Runtime.exec執行shell命令等方式才能獲取到當前進程的進程ID,今天在偶然中看到一種在Java程序里,獲取當前進程ID的方法,記錄下來,以后應該會用到:)
首先,從JDK1.5之后,Java開始提供包:java.lang.management
java.lang.management 提供了一系列的用來在運行時管理和監督JVM和OS的管理接口。
今天我將用到的就是這個包中的一個類:ManagementFactory。
獲取pid的程序代碼如下:
import sun.management.ManagementFactory;
// get name representing the running Java virtual machine.
String name = ManagementFactory.getRuntimeMXBean().getName();
System.out.println(name);
// get pid
String pid = name.split("@")[0];
System.out.println(“Pid is:” + pid);
輸出的結果如下:
25107@abc.mmm.xxx.yyy.com
Pid is :25107
第一行打印的是代表運行時JVM的一個名字,我們可以看到,這個名字是以進程pid開頭,以機器名結尾,中間用“@”連接而成的。
因此我們就可以從這個名字當中,截取出我們所需的pid了。
當然,這只是java.lang.management包中的一個小功能,該包還提供了很多其他的管理接口,參照java doc如下:
Interface Summary
ClassLoadingMXBean The management interface for the class loading system of the Java virtual machine.
CompilationMXBean The management interface for the compilation system of the Java virtual machine.
GarbageCollectorMXBean The management interface for the garbage collection of the Java virtual machine.
MemoryManagerMXBean The management interface for a memory manager.
MemoryMXBean The management interface for the memory system of the Java virtual machine.
MemoryPoolMXBean The management interface for a memory pool.
OperatingSystemMXBean The management interface for the operating system on which the Java virtual machine is running.
RuntimeMXBean The management interface for the runtime system of the Java virtual machine.
ThreadMXBean
