java - 在 Java 中启动、停止和监听进程

标签 java multithreading asynchronous process runtime

我想使用Runtime.exec()启动一个进程。然后我想知道(听)进程何时退出。另外,如果满足某些条件,我想手动停止该过程。

我现在的代码是:

public class ProcessManager extends Thread{
    private static ProcessManager manager;

    Process process;

    private ProcessManager(){

    }

    public static ProcessManager getInstance(){
        if(manager==null){
            manager=new ProcessManager();
        }
        return manager;
    }

    public void run(){
        Runtime runtime = Runtime.getRuntime();
        process = runtime.exec("c:\\windows\\system32\\notepad.exe");
        //cleanup();
    }
    public void cleanup(){
        //I want to do stuffs until the program really ends;
    }

    //called to manually stop the process
    public void stopProcess(){
        if(process!=null){
            //TODO: stop the process;
        }
    }
}

如代码所示,我的程序就像notepad.exe一样,弹出一个窗口并立即返回。如何监听程序的状态,并等待它关闭,以及显式关闭它?

最佳答案

How can I listen to the status of the program, and wait until it is closed, as well as close it explicitly?

您可以使用Process#waitFor()

// cause this process to stop until process p is terminated
         p.waitFor();

JavaDoc

The java.lang.Process.waitFor() method causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

关于java - 在 Java 中启动、停止和监听进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28980378/

相关文章:

java - Cloud endpoint api 中的函数 User.getUserId() 为不为 null 的用户对象返回 null

java - Android iText PDF 创建

java - 服务器在向 Spring Controller 发出几次请求后挂起

c# - 在 ASP.NET 中使用委托(delegate)来处理异步操作

multithreading - 从工作/子线程访问主 OMNET++ 模拟线程

node.js - 是否需要在异步调用中嵌套异步调用? ( Node .js)

java - 由于双重上下文 (servlet+ContextLoaderListener),所有 Spring Framework bean 都会重复

multithreading - 基于线程的服务器和基于事件的服务器有什么区别?

asynchronous - Guzzle,ReactPHP和Amphp进行并行请求

c# - 为什么我的异步回调在同一个线程中运行?