我希望在Java代码继续之前完成一个过程。 考虑代码
ProcessBuilder pb = new ProcessBuilder(COMMAND);
LOGGER.info(String.join(" ", COMMAND));
pb.redirectErrorStream(true);
Process cmdProces = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(cmdProces.getInputStream()));
String line;
while ((line = reader.readLine()) != null) System.out.println("tasklist: " + line);
boolean rc = cmdProces.waitFor(10, TimeUnit.SECONDS);
LOGGER.info("Script executed ");
因为这是在调度器内部,该调度器每30秒运行一次作业,所以进程没有在等待。我开始下一个命令。如何确保Java进程等待COMMAND
完成并且不会异步运行?
答案 0 :(得分:0)
也许使用Future是个好主意。
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> {
// some pb code
Process cmdProces = pb.start();
});
CompletableFuture<String> future = completableFuture
.thenApply(cmdProcess -> {
BufferedReader reader = new BufferedReader(new
InputStreamReader(cmdProces.getInputStream()));
String line;
while ((line = reader.readLine()) != null) System.out.println("tasklist: " + line);
boolean rc = cmdProces.waitFor(10, TimeUnit.SECONDS);
LOGGER.info("Script executed ");
});