使用java execute shell命令
这个类是响应执行命令,打印结果
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 . 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 .settings 2012-08-24 15:19 10,965 pom.xml 2012-08-07 10:57 src 2012-08-21 00:32 target 2012-08-24 10:22 0 velocity.log
为什么?
你开始了一个主题
executorThread.start();
如果你什么都不做,启动它的线程(你的主线程)将不会等到你的executorThread在返回之前完成,所以你的应用程序将在此线程执行其任务之前退出。
要等待您的executorThread完成,您应该致电:
executorThread.join();
稍后在代码中。 此时,您将确保它已完成任务。
目前它的工作原理是因为你在主线程中等待1秒钟,在此期间你的另一个线程执行它的动作。 但是如果你的executorThread需要超过一秒的时间来执行它,它将无法工作,所以在这种情况下你不应该sleep()
。
请参见Thread.join javadoc。
首先,为什么在不使用String时将String用作 execute()
方法中的参数 …
我尝试了你的程序稍作修改,它没有 sleep()
和interrupt()
试试下面的代码……
public final class ShellCommandExecutor{ public void execute(){ ExecutorTask task = new ExecutorTask(); Thread executorThread = new Thread(task); executorThread.start(); /*try { Thread.sleep(1000); executorThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); }*/ } public static void main(String[] args){ new ShellCommandExecutor().execute(); } } 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; } } }