在Java中执行外部程序 - 巨大的CPU负载

时间:2014-07-06 16:48:19

标签: java

我的程序中有这个代码:

        ProcessBuilder builder = new ProcessBuilder(command);

        builder.directory(new File(Vars.pathToForFfmpegBinDir));

        final Process process = builder.start();

        InputStream is = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("!!! "+line);
        }

因为外部程序获得了很多输出信息,所以它每while个周期加载100%的一个CPU核心。

我已尝试此代码的其他版本:

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectError(new File(pathToForModerationDir+"/1err.log"));
        builder.redirectOutput(new File(pathToForModerationDir+"/1inp.log"));
        builder.directory(new File(Vars.pathToForFfmpegBinDir));

        final Process process = builder.start();
        process.waitFor();

但它每个进程加载100%的一个CPU核心。

如何在此代码中减少CPU负载?

1 个答案:

答案 0 :(得分:0)

当我运行它时,我试图在top上找到它,但它使用的CPU不到0.1%,并且没有出现在我的用户ID的前20个进程中。

ProcessBuilder builder = new ProcessBuilder("sh", "-c", "while true; do sleep 1; date; done");
builder.redirectErrorStream(true);
final Process process = builder.start();

try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
    for (String line; (line = br.readLine()) != null; )
        System.out.println("!!! " + line);
}