在同一个Process对象上调用Runtime.getRuntime.exec(命令)两次

时间:2016-01-21 02:58:27

标签: java multithreading process centos

我有两个不同的命令(在外部EXE文件上),由两个String数组[linux@localhost Assignment1]$ gcc -c validate_acc.c In file included from validate_acc.c:2:0: validate_acc.h:5:23: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token int user_acc_try, i = 0; ^ validate_acc.c:6:20: error: expected ‘)’ before ‘va’ void (Validate_acc va) command1表示。我想在同一个线程中顺序运行这两个。具体而言,第一个命令执行10分钟。如果需要更长时间,请终止它并运行第二个命令。这就是我在做的事情。

command2

我实现的public class MyRunnable implements Runnable { private Process proc; private String[] command1; private String[] command2; public MyRunnable (String[] command1, String[] command2) { this.command1 = command1; this.command2 = command2; } public void run() { try { proc = Runtime.getRuntime().exec(command1); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); errorGobbler.start(); outputGobbler.start(); exitCode = proc.waitFor(10, TimeUnit.MINUTES); if (exitCode) System.out.println("Model " + modelPath + ": SUCCESSFULLY!"); else { System.out.println("Model " + modelPath + ": TIMED OUT!"); proc = Runtime.getRuntime().exec(command2); StreamGobbler errorGobbler1 = new StreamGobbler(proc.getErrorStream(), "ERROR"); StreamGobbler outputGobbler1 = new StreamGobbler(proc.getInputStream(), "OUTPUT"); errorGobbler1.start(); outputGobbler1.start(); proc.waitFor(10, TimeUnit.MINUTES); } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { proc.destroy(); } } } 类与此处www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html完全相同,以避免死锁。通常,它的作用是让另一个线程处理StreamGobbler对象的输出和错误流。

我不确定将两个不同的子流程分配给同一个Process对象是否合适。我观察到,即使在调用proc之后,command1的进程仍然运行,这会在一段时间后在我的计算机上创建大量进程。如何终止第一个命令的进程?我在CentOS 7上使用Java 1.8。

提前致谢。

1 个答案:

答案 0 :(得分:0)

if中,如果您到达else语句,则流程已超过超时,因此在将新流程分配给proc之前,您必须先终止上一个流程。在proc = proc.destroy()之前,proc.destroyForcibly()else添加了Runtime.getRuntime().exec(command2);语句中的任意一种方法有两种方法,它应该没问题。