簡體   English   中英

使用線程池運行多個進程的Java runtime.exec()

[英]Java runtime.exec() running multiple process using Threadpool

在我的程序中,我有一個n個測試腳本的列表,我需要迭代該列表並並行運行3個測試腳本。 為了完成此任務,我創建了一個大小為3的線程池。我的實現類似於下面的線程池

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:com.selenium.test.testname1由pool-1-thread-1執行

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

com.selenium.test.testname1任務ID:com.selenium.test.testname3由pool-1-thread-3執行

執行暫停在這里,它什么也沒做,我不確定后面發生了什么。 我還交叉檢查了該批處理文件是否工作正常。

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

public abstract int waitFor() throws InterruptedException

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

由於waitFor()是一個阻塞調用,所有3個線程都停留在此行。

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

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

也可以代替:

while (!executor.isTerminated()) {
}

您可以使用ExecutorService#awaitTermination()

讀取p.getInputStream()和p.getErrorStream()並將其而不是thread.sleep()寫入控制台,您將獲得線程正在執行的操作的指示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM