我以正确的方式退出线程时遇到了问题。我修改了一些代码,帮助我从我的代码中在Commandline窗口中运行可执行文件。在此之前,代码工作正常。问题是,在我调用的程序完成并返回命令行后,一个线程继续运行,如何获取完成的信息以及如何正确杀死它?我已经尝试了几个等待和通知的选项,但我无法让它们工作。谢谢你的帮助,这是我的代码:
public class InnExec {
String wkdir;
static String ActCommand;
static String InFile;
InnExec(String wkdir, String ActCommand, String InFile) {
InnExec.ActCommand=ActCommand;
this.wkdir=wkdir;
InnExec.InFile=InFile;
}
public Process Run() throws IOException, InterruptedException {
File wkdir=new File(this.wkdir);
ProcessBuilder processBuilder= new ProcessBuilder();
Boolean Windows=true;
if (!System.getProperty("os.name").contains("Windows")){
Windows=false;
}
if(Windows){
processBuilder.command("cmd.exe").redirectErrorStream(true);
}
else{
processBuilder.command("/bin/bash").redirectErrorStream(true);
}
processBuilder.directory(wkdir);
Process process = processBuilder.start();
Thread processOutputHandlerThread=createAndStartProcessOutputHandlerThread(process);
Thread processInputHandlerThread =createAndStartProcessInputHandlerThread(process);
return process;
}
private static Thread createAndStartProcessInputHandlerThread(final Process process) {
Thread thread = new Thread(new Runnable() {
public void run() {
PrintWriter printWriter = new PrintWriter(process.getOutputStream());
//Scanner scanner = new Scanner(System.in);
try {
printWriter.println(ActCommand+"<"+InFile);
printWriter.flush();
Thread.sleep(50);
}
catch (InterruptedException interruptedException) {
//
}
}
});
thread.start();
return thread;
}
private static Thread createAndStartProcessOutputHandlerThread(final Process process) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
char c = Character.MAX_VALUE;
while ((c = (char) process.getInputStream().read()) != Character.MAX_VALUE) {
System.out.print(c);
// Ausgabe auf Java Console
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return thread;
}
}
答案 0 :(得分:0)
您可以使用CountDownLatch
在main方法中,您可以定义您将拥有多少个线程,将其注入每个线程并等待它们完成。一旦线程完成,它将调用倒计时api,一旦你的所有线程完成,你的main方法可以继续进行。