我正在编写一个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,但没有任何作用...
任何帮助将不胜感激 :)
您可以读取输入流(即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 应该继续读取您已启动的进程的输出(只要它持续)。
请注意,上面只是伪代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)