从有时间限制的程序执行程序的多线程(Java)
我正在尝试制作一个运行一些可执行程序(称之为p
)的程序,给定时间限制t
ms。它执行以下任务:
- 如果程序
p
已正常执行,则将其输出打印到控制台李> - 如果程序
p
无法在时间限制内完全执行,请打印"Sorry, needs more time!"
,然后终止p
的执行李> - 如果程序
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 楼答案
根据java文档, 斯特杜特。stop()被弃用,甚至是stdout。destroy()从未实现
有关更多信息,请参阅为什么是线程。停下,Thread.suspend and Thread.resume Deprecated?.
你可以试试这个