有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从有时间限制的程序执行程序的多线程(Java)

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

  1. 如果程序p已正常执行,则将其输出打印到控制台
  2. 如果程序p无法在时间限制内完全执行,请打印"Sorry, needs more time!",然后终止p的执行
  3. 如果程序p异常终止(例如RuntimeError),则打印"Can I've some debugger?"

我在here的以下程序中使用ProcessResultReader类。只要p正常执行或异常终止,我的程序就会工作。但是,如果p本身没有在timeout之后终止,它就不会终止。(使用没有退出条件的简单while(true)循环尝试p)。即使在执行stdout.stop()之后,线程stdout仍然是活动的。我在这个代码中做错了什么

谢谢

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) 个答案

  1. # 1 楼答案

    根据java文档, 斯特杜特。stop()被弃用,甚至是stdout。destroy()从未实现

    有关更多信息,请参阅为什么是线程。停下,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?");
        }