繁体   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