[英]Running java runtime.exec() for multiple process
在我的程序中,我有一個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());
}
}
工序#WAITFOR()
如果需要,使當前線程等待,直到此Process對象表示的進程終止。 如果子進程已終止,則此方法立即返回。 如果子進程尚未終止,則調用線程將被阻塞,直到子進程退出。
你應該有四個線程,每個線程從一個池中獲取一個賦值,然后執行它,然后當它完成時,執行下一個賦值。 這將是如何:
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();
}
然后啟動其中四個線程。
您可以使用大小為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
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.