0

我可以在Process以下命令的帮助下启动,并且在启动多个进程后,我想控制我想在某个时候保留多少个进程。

例如:

  1. 在0 到 50 范围Process内的循环内启动for
  2. for活动进程总数为 5 后暂停循环
  3. 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\"");
    }
    
}

另外,如何找出有多少进程处于活动状态?这样我就可以一次控制活动进程。

4

1 回答 1

1

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()) { }
};
于 2020-09-05T16:44:10.877 回答