获取在后台运行的Java Runtime Process [英] Get Java Runtime Process running in background
问题描述
我正在编写一个Java应用程序,在该应用程序中,我需要在运行的应用程序的整个生命周期中在后台运行进程.
I'm writing a java application where I require to run a process in background throughout the lifetime of the running application.
这就是我所拥有的:
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()
.
So, basically I print out every br.readLine()
.
我不确定的事情是如何在应用程序中实现此代码,因为无论我将它放在哪里(与Runnable一起使用),它都会阻止其他代码运行(如预期的那样).
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).
我已经使用了Runnable,Thread,SwingUtilities,但没有任何效果...
I've used Runnable, Thread, SwingUtilities, and nothing works...
任何帮助将不胜感激:)
Any help would be greatly appreciated :)
推荐答案
您可以在线程中读取输入流(即br.readLine()
).这样,它始终在后台运行.
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:
// Did something...
InvokeScript.execute("sh blah.sh"); // Invoke the background process here. The arguments are taken in processed and executed.
// Continue doing what you were doing
InvokeScript.execute()如下所示:
InvokeScript.execute() will look something like below:
InvokeScript.execute(String args) {
// Process args, convert them to command array or whatever is comfortable
Process p = Runtime.getRuntime().exec(cmdArray);
ReaderThread rt = new ReaderThread(p.getInputStream());
rt.start();
}
ReaderThread应该继续读取您开始的进程的输出,只要它持续即可.
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.
这篇关于获取在后台运行的Java Runtime Process的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!