为多个进程运行 java runtime.exec()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18010604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:46:22  来源:igfitidea点击:

Running java runtime.exec() for multiple process

javaruntime.exec

提问by Vigneshwaran

In my program I do have a list of nitems.

在我的程序中,我确实有一个n项目列表。

I will be iterating the list and initiate a process like this:

我将迭代列表并启动这样的过程:

Runtime.getRuntime.exec("cmd /C start abc.bat"+listitem() )

I need to maintain a count of 4 processes. Once any one of the process is completed, I need to start the next process , so the process count should be 4.

我需要保持 4 个进程的计数。一旦任何一个进程完成,我需要开始下一个进程,所以进程数应该是4。

I am able to initiate 4 process simultaneously, but not sure on how to keep the count of 4. Basically I need some notification once a process is terminated, so I can start the next, any threading is possible.

我能够同时启动 4 个进程,但不确定如何保持 4 的计数。基本上,一旦进程终止,我需要一些通知,以便我可以开始下一个,任何线程都是可能的。

Any help on how to implement this, can somebody share a snippet on this above requirement?

关于如何实现这一点的任何帮助,有人可以分享关于上述要求的片段吗?

采纳答案by tbodt

You should have four threads that each take an assignment from a pool, then carry it out, then when it is done, carry out the next assignment. This would be how:

您应该有四个线程,每个线程从池中获取一个分配,然后执行它,然后在完成后执行下一个分配。这将是如何:

class Whatever extends Thread {
    public void run() {
        while (!interrupted()) {
            String str = listitem();
            if (str == null) // there are no more commands to run
                break;
            Runtime.getRuntime.exec(("cmd /C start abc.bat"+str).split("\s")).waitFor();
}

Then start four of these threads.

然后启动其中的四个线程。

回答by Tim Bender

Use an ThreadPoolExecutorof size 4 and a Runnableimplementation which starts the Processand then invokes Process.waitFor(). Since the thread pool will be restricted to 4 threads and all 4 threads will start a process and then wait for it, you'll be certain there won't be more than 4 child processes running.

使用ThreadPoolExecutor大小为 4 的 和Runnable启动Process然后调用 的实现Process.waitFor()。由于线程池将被限制为 4 个线程,并且所有 4 个线程都将启动一个进程然后等待它,因此您可以确定运行的子进程不会超过 4 个。

Some sample code to help you along your way:

一些示例代码可以帮助您一路走来:

ExecutorService executor = Executors.newFixedThreadPool(4);

executor.execute(new Runnable() {
    public void run() {
        //use ProcessBuilder here to make the process
        Process p = processBuilder.start();
        p.waitFor();
    }
});

回答by Narendra Pathai

 public class ProcessRunner {

    public static void main(String[] args) throws IOException, InterruptedException {
        //Creating n threads as required
        ExecutorService exec = Executors.newFixedThreadPool(4);
        for(int i = 0; i < 4; i++){
            exec.execute(new ProcessRunnable());
        }

        Thread.sleep(10000);

        //whenever you want them to stop
        exec.shutdownNow();

    }   

}

class ProcessRunnable implements Runnable{
       @Override
       public void run(){
        do{
           Process p;
        try {
            p = Runtime.getRuntime().exec("cd ..");
            p.waitFor(); 
        } catch (IOException e) {
                    //Take appropriate steps
            e.printStackTrace();
        } catch (InterruptedException e) {
                    //Take appropriate steps
            e.printStackTrace();
        }

        }while(!Thread.interrupted());
       }
}

Process#waitFor()

进程#waitFor()

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

使当前线程在必要时等待,直到此 Process 对象表示的进程终止。如果子进程已经终止,则此方法立即返回。如果子进程尚未终止,调用线程将被阻塞,直到子进程退出。

回答by Evgeniy Dorofeev

You can use fixed thread pool with size 4 which guarantees no more than 4 active threads at any given moment

您可以使用大小为 4 的固定线程池,以保证在任何给定时刻不超过 4 个活动线程

    final ExecutorService ex = Executors.newFixedThreadPool(4);
    for(int i = 0; i < 100; i++) {
        ex.execute(new Runnable() {
            @Override
            public void run() {
              ... run the process here and wait for it to end
            }
        });
    }