3

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

任何帮助将不胜感激 :)

4

1 回答 1

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 应该继续读取您已启动的进程的输出,只要它持续存在。

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

于 2010-09-14T16:55:33.037 回答