Java 9 改進的進程 API
在 Java 9 之前,Process API 仍然缺乏對使用本地進程的基本支持,例如獲取進程的 PID 和所有者,進程的開始時間,進程使用了多少 CPU 時間,多少本地進程正在運行等。
Java 9 向 Process API 添加了一個名為 ProcessHandle 的介面來增強 java.lang.Process 類。
ProcessHandle 介面的實例標識一個本地進程,它允許查詢進程狀態並管理進程。
ProcessHandle 嵌套介面 Info 來讓開發者逃離時常因為要獲取一個本地進程的 PID 而不得不使用本地代碼的窘境。
我們不能在介面中提供方法實現。如果我們要提供抽象方法和非抽象方法(方法與實現)的組合,那麼我們就得使用抽象類。
ProcessHandle 介面中聲明的 onExit() 方法可用於在某個進程終止時觸發某些操作。
實例
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
String np = "Not Present";
Process p = pb.start();
ProcessHandle.Info info = p.info();
System.out.printf("Process ID : %s%n", p.pid());
System.out.printf("Command name : %s%n", info.command().orElse(np));
System.out.printf("Command line : %s%n", info.commandLine().orElse(np));
System.out.printf("Start time: %s%n",
info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
.toLocalDateTime().toString()).orElse(np));
System.out.printf("Arguments : %s%n",
info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
System.out.printf("User : %s%n", info.user().orElse(np));
}
}
以上實例執行輸出結果為:
Process ID : 5800 Command name : C:\Windows\System32\notepad.exe Command line : Not Present Start time: 2017-11-04T21:35:03.626 Arguments : Not Present User: administrator