我有一个包含 2 个进程 java 的程序:processA 和 processB(2 个进程 java.exe 而不是 2 个线程)。 我使用进程 A 下面的代码块来调用进程 B 此代码包装在下面的 RunTask 类中
public class RunTask implements Callable<Object> {
private String runParams;
public String getRunParams() {
return runParams;
}
public void setRunParams(String runParams) {
this.runParams = runParams;
}
@Override
public Object call() throws Exception {
try {
//System.out.println("run:" + runParams);
Process procB = Runtime.getRuntime().exec("java -jar processB.jar);
DataInputStream ls_in = new DataInputStream(procB.getInputStream());
String ls_str;
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
}
} catch (Exception exp) {
exp.printStackTrace();
}
return null;
}
}
和主类我使用执行器
ExecutorService eservice = Executors.newSingleThreadExecutor();
while (1 == 1) {
String stringParams = getFilesNeedToImportAsString();
if (stringParams.trim().isEmpty()) {
long l1 = System.currentTimeMillis() - l;
System.out.println("all time" + l1 / 1000);
System.exit(100);
}
RunTask runTask = new RunTask();
runTask.setRunParams(SystemInfo.RUN_COMMAND + stringParams);
Future<Object> objectFuture = eservice.submit(runTask);
while (!objectFuture.isDone()) {
System.out.println("waiting the task running");
Thread.sleep(500);
}
}
但是当 processB 上发生异常时,两个进程(processA、processB)似乎都停止了,这是在 processB 上运行的代码
public Object call() {
try {
MutationResult result = mutator.execute();
return "ok";
} catch (Exception exp) {
exp.printStackTrace();
System.out.println("error on " + Thread.currentThread().getName() + "failed begin retry " + (++retryCount));
call();
System.out.println(retryCount + " completed");
return "ok";
}
}
如果我单独运行 processB(通过命令行)它永远不会发生,或者当这个问题发生时我使用 taskmanager 来杀死 proceesA(被调用者),processB 继续运行
请任何人给我这个问题的解决方案!!
最佳答案
你等着objectFuture
isDone
方法来完成。根据文档:
isDone: Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true
查看 processB 中的代码,当发生异常时执行 call()
再次递归。我知道你这样做是作为一种错误重试机制,但这是一个非常糟糕的主意,主要原因有两个:
- 如果异常仍然存在,你最终会得到一个 StackOverflowException
.
- 没有isDone
的条件会被满足的。
更好的选择是定义最大重试次数并尝试执行 mutator.execute()
.如果错误仍然存在,则抛出异常并完成执行。
另一种选择是等待 processB 完成最长时间,之后您可以通过调用 objectFuture.cancel(true)
取消任务的执行。 .
关于 processA 的一些评论:关于 RunTask
你不使用 runParams
这似乎是一些需要作为字符串导入的文件。此外,您使用 readLine()
在 DataInputStream
这是一种已弃用的方法。而是使用 InputStream
(例如 BufferedInputStream
)包裹在 InputStreamReader
中然后包裹在 BufferedReader
中- 然后调用 readLine()
在 BufferedReader
上.
关于java - 从另一个 java 进程调用 java 使其停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10958522/