在我的程序中,我有一个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由池-1-线程-1执行
com.selenium.test.testname1任务ID:com.selenium.test.testname2由池-1-线程-2执行
com.selenium.test.testname1任务ID:com.selenium.test.testname3由池-1-线程-3执行
执行在这里暂停了,它什么也没做,我不确定后面发生了什么。我还交叉检查了批处理文件是否正常工作。
该过程需要长才能执行,因此您的控制不会返回。
public abstract int waitFor() throws InterruptedException
如有必要,使当前线程等待,直到此process对象表示的进程终止。如果子流程已经终止,此方法将立即返回。如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。
由于waitFor()
是一个阻塞调用,所有3个线程都被阻塞在这一行。
注意:您不需要Thread.sleep(5000);
,因为waitFor()
本身就是阻塞性的。
尝试执行其他命令,看看控件是否返回。
也代替:
while (!executor.isTerminated()) {
}
您可以使用ExecutitorService#awaitTermination()
读取p.getInputStream()和p.getErrorStream()并将其写入控制台,而不是thread.sleep(),您将获得线程正在做什么的指示。