简体   繁体   English

运行批处理文件时 Java 程序挂起

[英]Java program hangs when running a batch file

I am using below the code to generate a report from input data.我使用下面的代码从输入数据生成报告。 When there is only a little data, the below code works fine.当只有很少的数据时,下面的代码工作正常。 But when the amount of data become greater, then my program hangs and have to kill the process using task manager to close the application.但是当数据量变大时,我的程序就会挂起,必须使用任务管理器来终止进程以关闭应用程序。

public void launchReport() {

    if( selectionRulesRespected ) {

        final Process p;

        final String userNameParLine = getUserNameParLine();
        final String injParLine = getFilterByFieldParLine();

        writeTmpParFile(tmpParFilePath, new String[]{userNameParLine, injParLine});

        try {
            final ProcessBuilder builder;
            if( exporting != null && "TRUE".equals(exporting.toUpperCase()) ) {
                builder = new ProcessBuilder("cmd", "/c", batFilePath, reportName, tmpParFilePath, exportFilePath);
            }
            else {
                builder = new ProcessBuilder("cmd", "/c", batFilePath, reportName, tmpParFilePath);
            }
            //builder.directory( new File(viewerDirPath));
            p = builder.start();
            p.waitFor();
        } catch (final IOException e) {
            PlanonMessageDialog.showErrorDialog(ioError);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }

    } else {
        PlanonMessageDialog.showErrorDialog(wrongItem);
    }
}

The application hangs because this method waits for the process to be completed.应用程序挂起,因为此方法等待进程完成。 What are the options that I can use for this?我可以使用哪些选项?

Your java code uses p.waitFor() to wait until the process terminated.您的 Java 代码使用 p.waitFor() 等待进程终止。 But the process writes to stdout/stderr, the buffer is full and thus Windows stops it from executing further - instead it waits for the buffer to be emtpied.但是进程写入 stdout/stderr,缓冲区已满,因此 Windows 阻止它进一步执行 - 相反,它等待缓冲区被清空。 Both processes wait for each other - that's a classic deadlock.两个进程互相等待——这是一个典型的死锁。

To prevent this, replace p.waitFor() with a loop that checks whether the process has exited.为防止出现这种情况,请将 p.waitFor() 替换为检查进程是否已退出的循环。 If not, read from both stdout and stderr.如果不是,则从 stdout 和 stderr 读取。

See also https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Process.html另请参见https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Process.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM