如何解决在Java中查找进程数
我能够在以下命令的帮助下启动Process
,并且在启动多个进程之后,我想控制在某个时刻要保留多少个进程。
例如:
- 在范围为0到50的
Process
循环内启动for
- 一旦活动进程总数为5,就暂停
for
循环 - 一旦
for
从5降到4或3,就继续循环...
我尝试使用下面的代码,但缺少一些内容。
public class OpenTerminal {
public static void main(String[] args) throws Exception {
int counter = 0;
for (int i = 0; i < 50; i++) {
while (counter < 5) {
if (runTheProc().isAlive()) {
counter = counter + 1;
}else if(!runTheProc().isAlive()) {
counter = counter-1;
}
}
}
}
private static Process runTheProc() throws Exception {
return Runtime.getRuntime().exec("cmd /c start cmd.exe /c \"dir && ping localhost\"");
}
}
此外,如何找出活动的进程数?这样我就可以一次控制活动进程。
解决方法
您可以使用固定大小的线程池。 例如:
public static void main(String[] args) throws Exception {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 50; i++) {
threadPool.submit(runTheProc);
}
}
private static final Runnable runTheProc = () -> {
Process process;
try {
process = Runtime.getRuntime().exec("cmd /c start cmd.exe /c \"dir && ping localhost\"");
} catch (Exception e) {
throw new RuntimeException(e);
}
while (process.isAlive()) { }
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。