首页 > 解决方案 > Process.waitFor() 不“等待”当前线程完成

问题描述

我有一个 excel 表,其中包含要执行的 jar 文件列表。为了开始测试,我将运行一个代码从上述 excel 表中读取并执行 excel 表中的 jar 文件。运行这些 jar 文件的代码如下:

final Process p = Runtime.getRuntime().exec("cmd /c start cmd /k java -jar " + start.jar_filepath + " " + start.tc_name + " " + start.test_data + " " + start.test_result + " " + start.test_cycle);

这实际上将同时运行所有 jar 文件。

我实际上希望一次执行一个 jar,并在当前 jar 完成执行后执行下一个 jar。

我添加了以下内容。

p.waitFor();

但是,它的行为仍然相同,即同时执行。

我是否错误地使用了 waitFor() ?建议表示赞赏。

更新:以下是迭代excel工作表的代码

public static void main(final String[] args) throws IOException, Throwable {
        final DataFormatter df = new DataFormatter();
        final FileInputStream StartInput = new FileInputStream("c:\\TA\\TestConfig_MA.xlsx");
        final XSSFWorkbook StartInputWB = new XSSFWorkbook(StartInput);
        final XSSFSheet sheet = StartInputWB.getSheet("Config");
        System.out.println("Amount of Row in test config : "+ sheet.getLastRowNum());
        start.count = 1;
        //while (start.count <= sheet.getLastRowNum()) {
        for(start.count = 1; start.count <= sheet.getLastRowNum(); start.count++){  
            System.out.println("Total test case = " + sheet.getLastRowNum());
            System.out.println(start.count);
            final XSSFRow row = sheet.getRow(start.count);
            start.testability = row.getCell(0).toString();            
            start.jar_filepath = row.getCell(1).toString();
            start.tc_name = row.getCell(2).toString();
            start.test_data = row.getCell(3).toString();
            start.test_result = row.getCell(4).toString();
            start.test_cycle = df.formatCellValue(row.getCell(5));
            System.out.println("test cycle from start.jar = " + start.test_cycle);
            System.out.println("Test Case Name : " + start.tc_name);
            if (start.testability.equals("Y") || start.testability.equals("y)")) {
                System.out.println("Test Case Name : " + start.tc_name);
                System.out.println("Round : " + start.count);
                final Process p = Runtime.getRuntime().exec("cmd /c start cmd /k java -jar " + start.jar_filepath + " " + start.tc_name + " " + start.test_data + " " + start.test_result + " " + start.test_cycle);
                p.waitFor();
                System.out.println("wait for = " +p.waitFor());
            else {
                System.out.println("Its a no");
            }
           // ++start.count;
        }//for
        System.out.println("test is done");
    }
   
    }

标签: javaprocesswait

解决方案


为什么需要"cmd /c start cmd /k ..."?你跑cmd哪跑start哪跑cmd哪跑java

特别是start打开一个新窗口并立即返回。因此p.waitFor();会等待start完成,而不是它打开的新窗口。

你可能想把它缩小到简单

...exec("java -jar " + ...)

或者至少

...exec("cmd /c java -jar " + ...)


推荐阅读