2

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    <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

why?

2
  • Did you try to close stream before exit? Commented Aug 25, 2012 at 11:14
  • Since you are working with exec, I think it would worth to take a look at Apache Exec library. Its really good and takes care of all the little things that need to done. commons.apache.org/exec Commented Aug 25, 2012 at 11:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much, but I still cann't understand why not the main thread not to end until the executorThead doen its work? but add executorThead.join()
sorry I cannot understand your question, could you rephrase?
i am sorry,forgive my poor english. I just say why not the main code exit until the executorThread finish the task?
@aviad thanks! @liuzhijun; that is the base of multithreading, you start a thread because what it performs can be run in parallel with what you perform and you do not need to wait that it finishes it taks before finishing yours. At some point though you need some synchronization mechanism (like join) to ensure all threads have fulfilled their part of the contract before going on. In your case for instance executorThread.join() will ensure your shell operation completed (successfuly or not).
0

First of all why are you using String as a parameter in execute() method when you are not using it...

I tried your program with slight modification and it worked without sleep() and interrupt()

Try the code below.....

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;
        }
    }
}

1 Comment

sorry,I change my code look like more clear right now ,so forget to remove this parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.