从具有时间约束的程序执行程序(Java)

时间:2015-04-28 15:24:15

标签: java multithreading process timeout

我尝试制作运行某些可执行程序的程序(称之为p),给定时间限制t ms。它执行以下任务:

  1. 如果程序p已正常执行,请将其输出到控制台。
  2. 如果程序p无法在时间限制内完全执行,请打印"Sorry, needs more time!",然后终止执行p
  3. 如果程序p异常终止(例如RuntimeError),请打印"Can I've some debugger?"
  4. 我在here的以下程序中使用ProcessResultReader类。只要p正常执行或异常终止,我的程序就会正常工作。但是,如果p本身在timeout之后没有终止,它就不会终止。(尝试使用简单p循环但没有退出条件的while(true))。似乎线程stdout在执行stdout.stop()后仍然存在。我在这段代码中做错了什么?

    感谢。

    import java.util.concurrent.TimeUnit;
    import java.io.*;
    
    class ProcessResultReader extends Thread
    {
    
        final InputStream is;
        final StringBuilder sb;
    
        ProcessResultReader(final InputStream is)
        {
            this.is = is;
            this.sb = new StringBuilder();
        }
        public void run()
        {
            try
            {
                final InputStreamReader isr = new InputStreamReader(is);
                final BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                {
                    this.sb.append(line).append("\n");
                }
            }
            catch (final IOException ioe)
            {
                System.err.println(ioe.getMessage());
                throw new RuntimeException(ioe);
            }
        }
    
        @Override
        public String toString()
        {
            return this.sb.toString();
        }
        public static void main(String[] args) throws Exception
        {
            int t = 1000; 
            Process p = Runtime.getRuntime().exec(cmd); //cmd is command to execute program p 
            ProcessResultReader stdout = new ProcessResultReader(p.getInputStream());
            stdout.start();
            if(!p.waitFor(t, TimeUnit.MILLISECONDS))
            {
                stdout.stop();
                p.destroy();
                System.out.println("Sorry, needs more time!");
            }
            else
            {
                if(p.exitValue()==0) System.out.println(stdout.toString());
                else System.out.println("Can I've some debugger?");
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

根据java文档, stdout.stop()已被弃用,甚至stdout.destroy()也从未实现过。

有关详细信息,请参阅为什么是Thread.stop,Thread.suspend and Thread.resume Deprecated?.

你可以试试这个。

String cmd="cmd /c sleep 5";
    int timeout = 1; 
    Process p = Runtime.getRuntime().exec(cmd); //cmd is command to execute program p 
    ProcessResultReader stdout = new ProcessResultReader(p.getInputStream());
    stdout.start();
    if(!p.waitFor(timeout, TimeUnit.MILLISECONDS))
    {
        stdout.stop();
        p.destroy();
        System.out.println("Sorry, needs more time!");
        System.out.flush();
    }
    else
    {
        if(p.exitValue()==0) System.out.println(stdout.toString());
        else System.out.println("Can I've some debugger?");
    }