我的程序中有一个由n
个项目组成的列表。
我将遍历这个列表,并启动如下进程:
Runtime.getRuntime.exec("cmd /C start abc.bat"+listitem() )
我需要维护4个进程的计数。一旦其中任何一个进程完成,我需要启动下一个进程,因此进程计数应为4。
我能够同时启动4个进程,但不确定如何保持计数为4。基本上,我需要一些通知来告诉我进程何时终止,以便我可以启动下一个进程,任何线程都可以。
关于如何实现这一点,有人能分享一段代码吗?
我的程序中有一个由n
个项目组成的列表。
我将遍历这个列表,并启动如下进程:
Runtime.getRuntime.exec("cmd /C start abc.bat"+listitem() )
我需要维护4个进程的计数。一旦其中任何一个进程完成,我需要启动下一个进程,因此进程计数应为4。
我能够同时启动4个进程,但不确定如何保持计数为4。基本上,我需要一些通知来告诉我进程何时终止,以便我可以启动下一个进程,任何线程都可以。
关于如何实现这一点,有人能分享一段代码吗?
使用大小为4的ThreadPoolExecutor
和一个Runnable
实现,该实现启动Process
并调用Process.waitFor()
。由于线程池将被限制为4个线程,并且所有4个线程都将启动进程然后等待它,因此您可以确保不会有多于4个子进程在运行。
以下是一些示例代码,可帮助您完成这项任务:
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();
}
});
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()
该方法会使当前线程等待,直到由该Process对象表示的进程终止。如果子进程已经终止,则此方法立即返回。如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。
shutdownNow()
。 - Narendra Pathaiclass 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();
}
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
}
});
}