How can a Java program get its own process ID?

后端 未结 22 2075
梦毁少年i
梦毁少年i 2020-11-22 03:47

How do I get the id of my Java process?

I know there are several platform-dependent hacks, but I would prefer a more generic solution.

22条回答
  •  旧时难觅i
    2020-11-22 04:17

    Since Java 9 there is a method Process.getPid() which returns the native ID of a process:

    public abstract class Process {
    
        ...
    
        public long getPid();
    }
    

    To get the process ID of the current Java process one can use the ProcessHandle interface:

    System.out.println(ProcessHandle.current().pid());
    

提交回复
热议问题