【问题标题】:using a timer to destroy/interupt a process in Java使用计时器销毁/中断Java中的进程
【发布时间】:2013-04-09 11:31:56
【问题描述】:

您好,我想知道如果进程经过了以毫秒为单位的预定义时间段,我如何使用计时器来销毁进程。

目前我有一个从运行时获取线程的方法

Runtime runtime = Runtime.getRuntime();

然后我创建单独的进程以使用运行时执行命令

 Process process = runtime.exec(comman); //where command is a string with a defined command

然后我在调用之前处理正常/错误输出流:

 process.waitFor(); 

这会等待进程终止(如果它尚未终止)。

我的问题是,如何在进程完成之前使用计时器终止进程,即通过调用:

 process.destroy;

基本上,如果该过程工作超过一定时间,我想过早地销毁它。

如果由于过度运行而被破坏,我会抛出一个 InterruptedException。

有人告诉我使用计时器是实现此目的的最佳方式,但不确定是否是这种情况?

任何帮助将不胜感激。

【问题讨论】:

标签: java multithreading process timer runtime


【解决方案1】:

试试

    final Process p = ...
    final Thread mainThread = Thread.currentThread();
    Thread t = new Thread() {
        public void run() {
            try {
                Thread.sleep(1000);
                p.destroy();
                mainThread.interrupt();
            } catch (InterruptedException e) {
            }
        };
    };
    p.waitFor();
    if (mainThread.isInterrupted()) {
        throw new InterruptedException();
    }
    t.interrupt();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多