【发布时间】:2015-04-28 15:24:14
【问题描述】:
我正在尝试制作运行一些可执行程序的程序(称之为p),给定时间限制t ms。它执行以下任务:
- 如果程序
p已经正常执行,打印输出到控制台。 - 如果程序
p不能在时限内完全执行,打印"Sorry, needs more time!"然后终止p的执行。 - 如果程序
p异常终止(例如RuntimeError),打印"Can I've some debugger?"
我在here 的以下程序中使用ProcessResultReader 类。只要p 正常执行或异常终止,我的程序就可以运行。但是,如果p 本身在timeout 之后没有终止,它不会终止。(尝试p 使用简单的while(true) 循环,没有退出条件)。即使在执行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?");
}
}
}
【问题讨论】:
-
我知道 this 并不是您正在寻找的东西,但它似乎可以帮助或至少为您指明正确的方向。
标签: java multithreading process timeout