Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การเปลี่ยนแปลง Core Library ของ Process API ใน Java 9

Java 9 เพิ่ม ProcessHandle และ ProcessHandle.Info สำหรับดึงข้อมูล process: PID, command, user, start time, CPU duration

ตัวอย่างโค้ด

import java.lang.ProcessHandle.Info;

public class ProcessAPIInfo {
    public void printInfo(ProcessHandle ph) {
        Info info = ph.info();
        System.out.println("Executable: " + info.command().orElse("N/A"));
        System.out.println("User: " + info.user().orElse("N/A"));
        System.out.println("Start Time: " + info.startInstant().orElse(null));
    }
    
    public static void main(String args[]) {
        System.out.println("Process API Core Library Changes");
        ProcessHandle current = ProcessHandle.current();
        System.out.println("Current PID: " + current.pid());
        new ProcessAPIInfo().printInfo(current);
        
        // แสดง process อื่น 4 ตัวแรก
        ProcessHandle.allProcesses()
            .filter(ph -> ph.info().command().isPresent())
            .limit(4)
            .forEach(ph -> new ProcessAPIInfo().printInfo(ph));
    }
}

ผลลัพธ์ตัวอย่าง

Current PID: 5724
Executable: C:\Program Files\Java\jdk-9.0.4\bin\java.exe
User: Tutorialspoint\User
Start Time: 2020-04-01T07:35:43.152Z
Executable: C:\WINDOWS\System32\taskhostex.exe
User: Tutorialspoint\User
Start Time: 2020-04-01T04:14:36.241Z
...