我正在尝试从Java文件运行异步bash命令,并等待其完成之后再继续执行Java代码。
此刻,我尝试像这样使用Callable
:
class AsyncBashCmds implements Callable{
@Override
public String call() throws Exception {
try {
String[] cmd = { "grep", "-ir", "<" , "."};
Runtime.getRuntime().exec(cmd);
return "true"; // need to hold this before the execution is completed.
} catch (Exception e) {
return "false";
}
}
}
我这样称呼它:
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(new runCPPinShell(hookResponse));
String isFinishedRunningScript = future.get();
谢谢!
答案 0 :(得分:1)
一种更简单的方法是使用Java 9+ .onExit()
:
private static CompletableFuture<String> runCmd(String... args) {
try {
return Runtime.getRuntime().exec(args)
.onExit().thenApply(pr -> "true");
} catch (IOException e) {
return CompletableFuture.completedFuture("false");
}
}
Future<String> future = runCmd("grep", "-ir", "<" , ".");
String isFinishedRunningScript = future.get(); // Note - THIS will block.
如果仍然要阻止,请使用.waitFor()
。