我想運行一個外部程序重複N次,每次等待輸出並處理它。由於順序運行速度太慢,我嘗試了多線程。 的代碼看起來是這樣的:我應該如何在Java中使用多線程執行外部命令?
public class ThreadsGen {
public static void main(String[] pArgs) throws Exception {
for (int i =0;i < N ; i++)
{
new TestThread().start();
}
}
static class TestThread extends Thread {
public void run() {
String cmd = "programX";
String arg = "exArgs";
Process pr;
try {
pr = new ProcessBuilder(cmd,arg).start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
pr.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
//process output files from programX.
//...
}
然而,在我看來,只有一個線程同時運行(通過檢查CPU使用率)。
我想要做的是獲取所有線程(除了正在等待programX完成的線程)工作嗎?我的代碼有什麼問題?
是否因爲pr.waitFor();
使主線程等待每個子線程?
謝謝。對不起,遲來的回覆 – 2011-06-07 13:32:49