java线程周期性地杀死一个进程

标签 java multithreading process

我有一个 java 类,当前通过以下方式启动脚本

Process proc = Runtime.getRuntime().exec(" run my script");

出于特定原因,这几乎一直在运行。如果脚本由于某种原因终止,java 类就会重新启动它。

现在我需要偶尔终止该进程。因此,我决定启动一个线程,让它等待特定时间,然后终止该进程。 java 主类或其他类仍然会看到进程终止,然后重新启动它。

我不知道如何让这个线程查看进程并随后经常杀死它。关于如何创建该线程有什么建议吗?需要注意的是,我已经有一段时间没有使用线程了,所以我有点生疏了。

我的类的简单伪代码,用于了解我正在做的事情的基本概念:

Class MyClass{

    Process mProc;

    main(args){
        do{
            try{
                mProc = Runtime.getRuntime().exec("cmd /C myScript");
                mProc.destroy();
            } catch(Exception e){
                Log(e);
            }
        } while(true);

最佳答案

I don't know how to get this thread to see the process and the to subsequently kill it every so often.

从 Java 6 开始,这目前并不容易做到。Process 类有一个 waitFor() 方法,但它不会超时,这是悲剧性的在内部它只是调用 wait() —— 至少在 UnixProcess 中是这样。

您可以做的(有点黑客行为)是在Process上同步并自己调用wait(timeoutMillis)。像这样的东西:

Process proc = new ProcessBuilder().command(commandArgs).start();
long startMillis = System.currentTimeMillis();
synchronized (proc) {
    proc.wait(someTimeoutMillis);
}
long diff = System.currentTimeMillis() - startMillis;
// if we get here without being interrupted and the delay time is more than
// someTimeoutMillis, then the process should still be running
if (diff >= someTimeoutMillis) {
   proc.destroy();
}

问题是存在竞争条件,如果进程在您同步 proc 之前完成,您将永远等待。另一种解决方案是在一个线程中执行 proc.waitFor() 操作,然后在超时到期后在另一个线程中中断它。

Process proc = new ProcessBuilder().command(commandArgs).start();
try {
   // this will be interrupted by another thread
   int errorCode = proc.waitFor();
} catch (InterruptedException e) {
   // always a good pattern to re-interrupt the thread
   Thread.currentThread().interrupt();
   // our timeout must have expired so we need to kill the process
   proc.destroy();
}
// maybe stop the timeout thread here

另一个选项是使用 proc.exitValue(),它允许您测试进程是否已执行。不幸的是,如果它还没有完成,它不会返回 -1 或抛出 IllegalThreadStateException 的东西。

关于java线程周期性地杀死一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16464670/

相关文章:

java - jTable paint() 导致 java.lang.OutOfMemoryError : Java heap space

java同步和共享表

c# - 是否有可能创建一个始终会自行清理的进程?

java - 无法弄清楚我在这个方法中做错了什么(compute_even)

java - 在eclipse中构建错误

Java 异常处理 - 风格

c - vfork() atexit 断言失败

c++ - 将参数从主线程传递到线程。当线程退出时,主线程重置为0。为什么?

java - 如何从多个线程中获取第一个结果并取消剩余

version-control - 版本控制 javadoc 的优缺点