这个类是执行命令的响应,打印结果
public class ExecutorTask implements Runnable{
@Override
public void run() {
Process process = null;
try {
process = Runtime.getRuntime().exec("cmd /c dir");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line="";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
return;
}
}
}
第二个类是执行器,使用线程运行 shell
public final class ShellCommandExecutor{
public void execute(String command){
ExecutorTask task = new ExecutorTask();
Thread executorThread = new Thread(task);
executorThread.start();
/*try {
Thread.sleep(1000);
executorThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
问题是为什么我必须在 ShellCommandExecutor 类中添加代码片段:
try {
Thread.sleep(1000);
executorThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
然后我可以看到打印结果:
2012-08-21 00:32 <DIR> .
2012-08-21 00:32 <DIR> ..
2012-08-21 00:32 1,576 .classpath
2012-08-21 00:26 1,224 .project
2012-08-07 10:58 <DIR> .settings
2012-08-24 15:19 10,965 pom.xml
2012-08-07 10:57 <DIR> src
2012-08-21 00:32 <DIR> target
2012-08-24 10:22 0 velocity.log
为什么?