2013-08-05 100 views
1

在我的程序中,我有一個n測試腳本的列表,我需要迭代列表並運行3個並行的測試腳本。爲了實現這一任務,我創建了尺寸3的線程池我的實現是像下面的線程池使用Threadpool運行多個進程的Java runtime.exec()

ExecutorService executor = Executors.newFixedThreadPool(3); 
for (int threadpoolCount = 0; threadpoolCount < classNames.size(); threadpoolCount++) { 
    Runnable worker = new ProcessRunnable(classNames.get(threadpoolCount)); 
    executor.execute(worker); 
} 
executor.shutdown(); 
while (!executor.isTerminated()) { 
} 

System.out.println("Finished all threads"); 
下面

是我的線程執行其中我在它執行與Maven命令的批處理文件

public void run() { 
    try { 
     System.out.println(testname); 
     System.out.println("Task ID : " + this.testname + " performed by " + Thread.currentThread().getName()); 
     Process p = Runtime.getRuntime().exec("cmd /C Junit_runner.bat" + " " + testname); 
     p.waitFor(); 
     Thread.sleep(5000); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

以下是我在控制檯中看到(我不是在啓動命令提示符,然後在後臺運行它)

com.selenium.test.testname1 任務ID:由池-1-線程1

com.selenium.test.testname1 任務ID進行com.selenium.test.testname1 :com.selenium.test.testname2 由pool-執行1線程2

com.selenium.test.testname1 任務ID:由池-1-線程3

進行com.selenium.test.testname3 執行暫停這裏,它沒有做任何事情,我不是sur e背後發生了什麼。我也交叉檢查批處理文件的工作正常。

+0

運行'Junit_runner.bat'需要多長時間? – Jatin

+0

需要2到3分鐘才能完成執行和termiante,她的e是我的批處理文件命令。 ** @ Echo off echo%1 call mvn -f pom。xml test -Dtest =%1 exit ** – Vigneshwaran

回答

2

該過程需要才能執行,因此您的控件不會返回。

public abstract int waitFor() throws InterruptedException 

導致當前線程在必要時等待,直到此Process對象表示的進程終止。如果子進程已經終止,則此方法立即返回。如果子進程尚未終止,則調用線程將被阻塞,直到子進程退出。

由於waitFor()是一個阻塞調用,所有3個線程都卡在這條線上。

注意:您不需要Thread.sleep(5000);因爲waitFor()本身就是阻塞的。

嘗試執行一些其他命令,看看控制是否返回。

而且代替:

while (!executor.isTerminated()) { 
} 

您可以使用ExecutorService#awaitTermination()

+0

忘記提及,如果我在執行阻塞之後終止執行,批處理文件將啓動所有三個線程。 – Vigneshwaran

+0

@ user2644818我沒弄明白,你能不能詳細說一下? –

+0

正如我在我的問題中發佈一旦執行開始啓動三個進程並暫停很長時間,後殺死執行我從Runtime.exec(「」)調用的批處理文件啓動 – Vigneshwaran

0

閱讀p.getInputStream()和p.getErrorStream(),並將其寫入到控制檯,而不是Thread.sleep()方法,你將會看到線程正在做什麼。

相關問題