java中的多线程查找进程计数

3b6akqbq  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(321)

我可以发射 Process 在下面命令的帮助下,在启动多个进程之后,我想控制在某个点上要保留多少进程。
例如:
启动 Process 内部 for 范围为0到50的回路
暂停 for 活动进程总数为5时循环
简历 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\"");
    }

}

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

km0tfn4u

km0tfn4u1#

可以使用固定大小的线程池。例如:

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()) { }
};

相关问题