我使用 Runnable 对象来运行 processCommand 并执行一些需要一定时间的处理(我们将其称为“进程内部”)。在内部进程结束时,它将向文本文件写入一些内容。我的想法是,如果在指定时间内内部进程仍未完成,则必须将其终止,因此我使用 ExecutorService 来处理它。但如果内部进程早于指定时间完成,它将中断 ExecutorService,以便主线程可以继续执行下一个任务。
但问题是,有时,内部进程根本不创建文件,或者创建文件但里面没有写入任何内容。当内部进程早于指定时间完成时,就会发生这种情况。我不知道我的实现有什么问题。请注意,如果我手动执行该过程(不使用 ExecutorService),则该过程运行良好并且可以正确写入所有内容。
在这里我发布我的代码来完成这项工作:
public void process(){
for (int i = 0; i < stoppingTime.length; i++) {
for (int j = 2 * i; j < 2 * (i + 1); j++) {
final int temp = j;
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable r = new Runnable() {
@Override
public void run() {
Process p = null;
int ex = 1;
try {
p = Runtime.getRuntime().exec(
processCommand.get(temp));
while (ex != 0) {
try {
//sleep every 30 second then check the exitValue
Thread.sleep(30000);
} catch (InterruptedException e) {
}
ex = p.exitValue();
p.destroy();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("IOException");
}
}
};
Future future = executor.submit(r);
try {
System.out.println("Started..");
future.get(stoppingTime[i], TimeUnit.SECONDS);
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
} catch (InterruptedException e) {
System.out.println("Future gets InterruptedException");
} catch (ExecutionException e) {
System.out.println("Future gets ExecutionException");
}
executor.shutdownNow();
System.out.println("shutdown executor");
}
System.out.println();
}
}
最佳答案
老问题,我想我还是会尝试一下。
首先,您将在双循环内获得一个 ExecutorService
,与定义的 Runnable
位于同一 block 中。如果您想获取 native 执行 "processCommand"
的返回值,然后像您所说的那样继续执行下一个任务,那么您需要通过实例化来重用该 ExecutorService
在循环之前。
其次,stoppingTime[i]
是 int
而 Future.get(...)
需要 long
.
关于java - 使用executorservice控制运行时进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13968082/