让Java Runtime Process在后台运行

时间:2010-09-14 16:47:40

标签: java process runtime background-process runtime.exec

我正在编写一个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,没有任何作用......

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:2)

您可以在线程中读取输入流(即br.readLine())。这样,它总是在后台运行。

我们在应用程序中实现这一点的方式大致如下:

业务逻辑,即您调用脚本的位置:

// 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(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应该继续读取您已经开始的进程的输出,只要它持续。

请注意,以上只是伪代码。