excute java,使用java execute shell命令

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值