Java获取当前所在进程的PID

package jtest;
02 import java.lang.management.ManagementFactory;
03 import java.lang.management.RuntimeMXBean;
04 import javax.management.MBeanServer;
05 import javax.management.ObjectName;
06 /**
07  * 不同平台和版本下,Mbeans名字不一样。本例为win32+jdk 7_b07
08  * Author:源自网络
09  * Date:2012-12-9 下午7:18:29
10  */
11 public class MBeanAccess {
12     public static void main(String[] args) throws Exception {
13         //打印GC次数
14         MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
15         ObjectName youngMBean = newObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact");
16         ObjectName tenuredMBean = newObjectName("java.lang:type=GarbageCollector,name=Copy");
17         System.out.println("YGC:" + mbs.getAttribute(youngMBean,"CollectionCount"));
18         System.out.println("FGC:" + mbs.getAttribute(tenuredMBean,"CollectionCount"));
19         System.gc();
20         System.out.println("YGC:" + mbs.getAttribute(youngMBean,"CollectionCount"));
21         System.out.println("FGC:" + mbs.getAttribute(tenuredMBean,"CollectionCount"));
22         int pid = getPid(); 
23         System.out.println("pid: " + pid); 
24         //System.in.read(); // block the program so that we can do some probing on it 
25     }
26      
27     private static int getPid() {
28         //获取进程的PID
29         RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); 
30         String name = runtime.getName(); // format: "pid@hostname" 
31         try { 
32             return Integer.parseInt(name.substring(0, name.indexOf('@'))); 
33         } catch (Exception e) { 
34             return -1; 
35         } 
36     } 
37 }

你可能感兴趣的:(Java获取当前所在进程的PID)