this class is response to execute the command ,the print the result
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;
}
}
}
the second class is a executor to run the shell use a thread
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();
}*/
}
}
the problem is why i must in the class ShellCommandExecutor add code snippet:
try {
Thread.sleep(1000);
executorThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
then can i see the print result:
2012-08-21 00:32
2012-08-21 00:32
2012-08-21 00:32 1,576 .classpath
2012-08-21 00:26 1,224 .project
2012-08-07 10:58
2012-08-24 15:19 10,965 pom.xml
2012-08-07 10:57
2012-08-21 00:32
2012-08-24 10:22 0 velocity.log
why?
解决方案
You started a thread with
executorThread.start();
if you do nothing else the thread that started it (your main thread) will not wait for your executorThread to finish before returning, so your application will exit before this thread has executed its task.
To wait for your executorThread to finish you should call:
executorThread.join();
later in the code. At this point you will be ensured that it has finished its task.
Currently it works because you wait for 1 second in your main thread, during this second your other thread performs its action. But if your executorThread needed more than one second to perform it it will not work, so you should not sleep() in this case.
See Thread.join javadoc.