问题描述
我能够在以下命令的帮助下启动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()) { }
};