英文:
Find Process Count in Java
问题
我可以使用以下命令启动Process
,在启动多个进程后,我想控制在某一点上要保留多少个进程。
例如:
- 在0到50的范围内,在
for
循环中启动一个Process
。 - 当总活动进程为5时,暂停
for
循环。 - 一旦从5下降到4或3,恢复
for
循环。
我尝试了下面的代码,但是似乎漏掉了一些内容。
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\"");
}
}
此外,如何找出有多少个活动进程?以便我可以同时控制活动进程数量。
英文:
I am able to launch Process
with the help of below command and after launching multiple processes I want to control how many processes I want to keep at some point.
For example:
- Initiate a
Process
inside afor
loop of range 0 to 50 - Pause the
for
loop once total active processes are 5 - Resume
for
loop once it drop from 5 to 4 or 3 ...
I tried below code, but I am missing something.
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\"");
}
}
Also, how to find out how many process are active? So that I can control active processes at a time.
答案1
得分: 1
你可以使用具有固定大小的线程池。
例如:
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()) { }
};
英文:
You can use thread pool with fixed size.
For example:
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()) { }
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论