java-如何使用带有参数的exitValue()?
作者:互联网
一篇很好的文章(当Runtime.exec()不会)说:您唯一可能使用exitValue()而不是waitFor()的时间是当您不希望您的程序阻塞在某个外部进程上等待时,可能永远不会完成.与其使用waitFor()方法,不如将一个名为waitFor的布尔参数传递给exitValue()方法,以确定当前线程是否应等待.布尔值会更有益,因为exitValue()是此方法的更合适的名称,并且两个方法不必在不同的条件下执行相同的功能.这种简单的条件判别是输入参数的领域.
我的情况完全相同,我的系统调用将启动一个进程,该进程将一直运行,直到用户决定杀死它为止.如果我使用'(process.waitFor()== 0)’,它将在此阻止程序,因为进程将无法完成.以上文章的作者建议exitValue()可以与“ waitFor”参数一起使用.有人尝试过吗?任何示例都将有所帮助.
码:
//启动ProcessBuilder,“ str”包含命令
ProcessBuilder pbuilder = new ProcessBuilder(str);
pbuilder.directory(new File("/root/workspace/Project1"));
pbuilder.redirectErrorStream(true);
Process prcs = pbuilder.start();
AForm.execStatustext.append("\n=> Process is:" + prcs);
// Read output
StringBuilder out = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(process.getInputStream()));
String current_line = null, previous_line = null;
while ((current_line = bfrd.readLine()) != null) {
if (!line.equals(previous_line)) {
previous_line = current_line;
out.append(current_line).append('\n');
//System.out.println(line);
}
}
//process.getInputStream().close();
// Send 'Enter' keystroke through BufferedWriter to get control back
BufferedWriter bfrout = new BufferedWriter(new OutputStreamWriter(prcs.getOutputStream()));
bfrout.write("\\r");
bfrout.newLine();
bfrout.flush();
bfrout.write("\\r");
bfrout.newLine();
bfrout.flush();
//process.getOutputStream().close();*/
if (prcs.waitFor() == 0)
System.out.println("Commands executed successfully");
System.exit(0);
解决方法:
在主线程中使用waitFor之前,请创建另一个线程(子代),并在此新线程中为终止情况构造逻辑.例如,等待10秒.
如果满足条件,则从子线程ant中断主线程,并在主线程上处理以下逻辑.
以下代码创建一个子线程来调用该进程,主线程执行其工作,直到子进程成功完成.
import java.io.IOException;
public class TestExecution {
public boolean myProcessState = false;
class MyProcess implements Runnable {
public void run() {
//------
Process process;
try {
process = Runtime.getRuntime().exec("your command");
process.waitFor();
int processExitValue = process.exitValue();
if(processExitValue == 0) {
myProcessState = true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void doMyWork() {
MyProcess myProcess = new MyProcess();
Thread myProcessExecuter = new Thread(myProcess);
myProcessExecuter.start();
while(!myProcessState) {
// do your job until the process exits with success
}
}
public static void main(String[] args) {
TestExecution testExecution = new TestExecution();
testExecution.doMyWork();
}
}
标签:processbuilder,java,nonblocking 来源: https://codeday.me/bug/20191009/1882749.html