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:windowssystem32notepad.exe command line : not present start time: 2017-11-04t21:35:03.626 arguments : not present user: administrator
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!