In my program I do have a list of n
items.
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.
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.
Any help on how to implement this, can somebody share a snippet on this above requirement?
Use an ThreadPoolExecutor
of size 4 and a Runnable
implementation which starts the Process
and 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.
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With