获取在后台运行的 Java 运行时进程
我正在编写一个java应用程序,我需要在正在运行的应用程序的整个生命周期中在后台运行一个进程。
这就是我所拥有的:
Runtime.getRuntime().exec("..(this works ok)..");
Process p = Runtime.getRuntime().exec("..(this works ok)..");
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
所以,基本上我打印出了每个 br.readLine() 。
我不确定的是如何在我的应用程序中实现此代码,因为无论我将其放在何处(使用 Runnable),它都会阻止其他代码运行(如预期)。
我使用过 Runnable、Thread、SwingUtilities,但没有任何效果...
任何帮助将不胜感激:)
I'm writing a java application where I require to run a process in background throughout the lifetime of the running application.
Here's what I have:
Runtime.getRuntime().exec("..(this works ok)..");
Process p = Runtime.getRuntime().exec("..(this works ok)..");
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
So, basically I print out every br.readLine()
.
The thing that I'm not sure about is how to implement this code in my application because wherever I put it (with Runnable), it blocks other code from running (as expected).
I've used Runnable, Thread, SwingUtilities, and nothing works...
Any help would be greatly appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在线程中读取输入流(即
br.readLine()
)。这样,它始终在后台运行。我们在应用程序中实现此功能的方式大致如下所示:
业务逻辑,即调用脚本的位置:
InvokeScript.execute() 将如下所示:
ReaderThread 应该继续读取您已启动的进程的输出,只要它持续下去。
请注意,上面只是伪代码。
You can read the input stream(i.e
br.readLine()
) in a thread. That way, it's always running in the background.The way we have implemented this in our application is roughly like below:
Business logic, i.e the place where you invoke the script:
InvokeScript.execute() will look something like below:
ReaderThread should continue reading the output of the process you have started, as long as it lasts.
Please note that the above is only a pseudo code.