在 Java 中并行化阻塞调用
我目前正在使用下面的代码来运行一个进程并从我自己的程序中打印其输出。我的问题是我想做的不仅仅是打印输出。但是,由于正在执行的 Process 几乎不会将输出打印到控制台,因此注释行几乎永远不会执行,因为 readLine() 方法是阻塞的。
Process p = Runtime.getRuntime().exec(executablePath);
ProcessWatcher pw = new ProcessWatcher(p);
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
while(!pw.isFinished()) {
String line = output.readLine();
if(line != null) {
System.out.println(line);
}
// I want to do something in parallel here
}
如果我可以给 readLine() 调用某种超时,或者如果我可以在它自己的线程中运行它,我的问题就会得到解决。后者是首选,但前者也是可以接受的。我的主要目的是保持代码简单。
有没有一种很好、简单的方法来并行化阻塞调用,或者我是否需要为此创建一个实现 Runnable 的新类?
I am currently using the below code to run a process and print its output from within my own program. My problem is that I'd like to do more than just print the output. However, since the Process being executed scarcely prints output to the console, the commented line is almost never executed because the readLine() method is blocking.
Process p = Runtime.getRuntime().exec(executablePath);
ProcessWatcher pw = new ProcessWatcher(p);
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
while(!pw.isFinished()) {
String line = output.readLine();
if(line != null) {
System.out.println(line);
}
// I want to do something in parallel here
}
My problem would be solved if I could give the readLine() call some sort of timeout, or if I could run it in its own Thread. The latter would be preferred, but the former is acceptable. My primary intention is to keep the code simple.
Is there a nice, simple way to parallelize a blocking call, or will I need to create a new class that implements Runnable just for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将代码包装起来。
您无法执行非阻塞 readLine 或超时操作。无论如何,编写处理非阻塞连接的代码通常要复杂 10 倍。 ;)
You can wrap you code with.
You cannot do a non-blocking readLine or one with a timeout. In any case, writing code to handle non-blocking connections is usually 10x more complex. ;)
readLine()
调用确实是阻塞的,但是,BufferedReader
上的ready()
调用却不是——所以你可以检查你的阅读器是否阻塞准备好(非阻塞调用),然后执行读取——类似这样:这将允许您在进程运行时在
while
循环中执行其他操作。The
readLine()
call indeed is blocking however, theready()
call on theBufferedReader
is not -- so you can check if your reader is ready (non-blocking call) and then perform a read -- something like that:This will allow you to execute something else in the
while
loop while the process is running.IMO,您最好将“进程”生成内容放在单独的执行线程中,因为生成进程可能需要不确定的时间,更不用说可能会出现很多问题。将所有这些东西捆绑在一个单独的逻辑单元中会更加干净。
IMO, you'd be better off putting the "process" spawning stuff in a separate thread of execution since spawning a process can take an indeterminate amount of time, not to mention a plethora of things that can go wrong with it. Having all those stuff bundled in a separate logical unit would be much more cleaner.