PID ,也就是进程ID。
方式1
import java.lang.management.ManagementFactory;
public class TestGetPid {
public static void main(String[] args) {
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
System.out.println("NAME = " + jvmName);
long pid = Long.valueOf(jvmName.split("@")[0]);
System.out.println("PID = " + pid);
}
}
运行结果示例:
NAME = 31743@Myhost
PID = 31743
方式2
对于 Java 9 及以上版本可以这样写:
public class TestGetPid {
public static void main(String[] args) {
long pid = ProcessHandle.current().pid();
System.out.println("pid = " + pid);
}
}
ProcessHandle 的具体介绍见:https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html