gpt4 book ai didi

Java线程题——监听n个错误流

转载 作者:行者123 更新时间:2023-11-30 12:01:03 24 4
gpt4 key购买 nike

首先让我说一下,我在线程方面的经验很低。

我有一个应用程序可以通过 Runtime.exec 方法启动其他几个 Java jar。问题是启动的 jar 需要同时运行,但是为了获得启动的 jar 的错误流,您基本上必须有一个循环“坐着听”,直到过程完成。

这是我现在拥有的:

_processes.add( Runtime.getRuntime().exec( commandList.toArray( new String[ commandList.size() ] ) ) );
Thread thread = new Thread( new Runnable() {
private final int _processNumber = _processes.size() - 1;
public void run() {
String streamData = _processNumber + " : ";
streamData += "StdError [\r";
BufferedReader bufferedReader =
new BufferedReader( new InputStreamReader( _processes.get( _processNumber ).getErrorStream() ) );
String line = null;
try {
while ( ( line = bufferedReader.readLine() ) != null ) {
streamData += line + "\r";
}
bufferedReader.close();
streamData += "]\r";
LOG.error( streamData );
}
catch ( Exception exception ) {
LOG.fatal( exception.getMessage() );
exception.printStackTrace();
}
}
} );
thread.start();

谁能解释如何让“错误流监听器线程”正常工作?

TIA

最佳答案

不使用 Runtime.getRuntime().exec(),而是使用 Process启动外部流程。这会让您的生活变得更加轻松。

我的项目中的示例代码:

    //Build command 
List<String> commands = new ArrayList<String>();
commands.add("my_application");
commands.add("arg1");
commands.add("arg2");
log.debug("{}", commands);

//Run command with arguments
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(directory);
pb.redirectErrorStream(true);
Process process = pb.start();

//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader
(process.getInputStream()));

//Only log unique lines (you might not need this)
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
log.debug(line);
}

//Check result
if (process.waitFor() == 0)
return 0;

//Abnormal termination: Log command parameters and output and throw ExecutionException
log.error("{}", commands);
log.error("\n{}", out.toString());
throw new ExecutionException(new IllegalStateException("MyApplication exit code 1"));

关于Java线程题——监听n个错误流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1235742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com