java 执行cmd命令时,如何设置最大执行时间,若超时则终止命令
public static String run(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
StreamCaptureThread errorStream = new StreamCaptureThread(p.getErrorStream());
StreamCaptureThread outputStream = new StreamCaptureThread(
p.getInputStream());
new Thread(errorStream).start();
new Thread(outputStream).start();
p.waitFor();
String result =command+"\n"+ outputStream.output.toString()
+ errorStream.output.toString();
System.out.print(result);
return result;
} catch (Exception e) {
e.printStackTrace();
return "null";
}
}
因为有时候Process p = Runtime.getRuntime().exec(command);p.waitFor();执行命令时会导致p出现假死状态,而导致该命令无法自行终止;
我希望能够通过某种方式设置10分钟的最大等待时间,若超过10分钟,则终止进程p。
还望大家能够给出实现方式或者思路; java cmd 最大执行时间 超时 最大等待时间 --------------------编程问答-------------------- 在线等待help~大家给予关注啊,感谢! --------------------编程问答-------------------- 在线等待help~大家给予关注啊,感谢!为什么这么冷~ --------------------编程问答--------------------
等待中 --------------------编程问答-------------------- Timer? --------------------编程问答--------------------
import java.util.concurrent.*;
public class ProcessExample {
public static void main(final String... args) {
final Callable<Process> task = new Callable<Process>(){
@Override public Process call() throws Exception {
return Runtime.getRuntime().exec("C:\\WINDOWS\\system32\\notepad.exe");
}
};
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Future<Process> result = scheduler.submit(task);
final Runnable checker = new Runnable(){
@Override public void run(){
Process p = null;
int exitValue = 0;
try {
p = result.get();
exitValue = p.exitValue();
} catch (IllegalThreadStateException|InterruptedException|ExecutionException xe) {
if(p != null)p.destroy();
}
scheduler.shutdownNow();
System.exit(exitValue);
}
};
scheduler.schedule(checker, 10, TimeUnit.MINUTES);
}
}
补充:Java , Java相关