【问题标题】:Get Java Runtime Process running in background让 Java 运行时进程在后台运行
【发布时间】:2010-09-14 16:47:40
【问题描述】:

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

任何帮助将不胜感激:)

【问题讨论】:

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


    【解决方案1】:

    您可以在线程中读取输入流(即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 应该继续读取您已启动的进程的输出,只要它持续存在。

    请注意,以上仅为伪代码。

    【讨论】:

    • 感谢 pavanlimo,关于何时何地启动进程的任何建议 = Runtime.getRuntime().exec(?
    • 非常感谢 pavanlimo,我已经在浏览器上测试了代码,它的工作原理非常棒,但我实际上是在为 Java 桌面应用程序寻找一些东西。你知道java中InvokeScript和ReaderThread的等价物吗?
    • @phillyville,如果还不清楚,ReaderThread 和 InvokeScript 应该是您自己的 Java 类。 :)
    • 是的,我认为 :) 我创建了一个新的 Thread 类来完成这项工作。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2023-03-10
    • 2013-11-23
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多