使用Java代碼獲取Java進程ID的方法


需要jre/lib下的tools.jar包

public class Test {

    public static void main(String[] args) throws Exception {
        // System.out.println(getPidFromWindows("javaw"));
        // 獲取監控主機
        /*MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
        // 取得所有在活動的虛擬機集合
        Set<Object> vmlist = new HashSet<Object>(local.activeVms());
        // 遍歷集合,輸出PID和進程名
        for (Object process : vmlist) {
            MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
            // 獲取類名
            String processname = MonitoredVmUtil.mainClass(vm, true);
            System.out.println(process + " ------> " + processname);
        }
        
        List<String> list = new ArrayList<String>();
        System.out.println(list.size());*/
        List<String> list = getPid();
        System.out.println(list);

    }
    
    public static List<String> getPid(){
        List<String> list = new ArrayList<String>();
        try {
            // 獲取監控主機
            MonitoredHost local;
            local = MonitoredHost.getMonitoredHost("localhost");
            // 取得所有在活動的虛擬機集合
            Set<Object> vmlist = new HashSet<Object>(local.activeVms());
            // 遍歷集合,輸出PID和進程名
            for (Object process : vmlist) {
                MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
                // 獲取類名
                String processname = MonitoredVmUtil.mainClass(vm, true);
                System.out.println(process + " ------> " + processname);
                if (processname.endsWith("stable.jar")) {
                    list.add(((Integer)process).toString());
                }
            }
        } catch (MonitorException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return list;
        
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM