views:

57

answers:

2

Let's say,

I have a Java class JavaClass1.java.I am executing 2 batch files from this Java class. Each .bat files starts another Java application. Lets say these other two app takes 15 hour each to complete, and they are also not dependent to each other.

How can I solve this issue. I dont have to wait for one to complete so that I have to start another, I can do it simultaneously also.

I found people talking about handelling outputstream, inputstream and error stream, if I wait for the errors to handle, then I have to wait 15 hours for each. I dont want to do that.

Is there any way? Please suggest. Thanks

+2  A: 

Place the mechanism for launching each .bat in its own thread, then start each thread.

    new Thread(new Runnable() {
        @Override
        public void run() {
            //Launch first bat.
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            //Launch second bat.
        }
    }).start();
Mike
what about handeling the threads...DO I have to get worry about it?
I edited to post some code. I just used anonymous classes. So apparently no worries.
Mike
dont I have to destroy the thread once i created. sorry for asking but i dont know much about threads. or could you explain about consequences about the above code snippet.
Java will garbage collect it, so you don't have to destruct it. The thread will die after run() completes. Each call start() will happen one after the other, sequentially. It will start a new thread, separate from the main thread of control, and continue its work.
Mike
what happens if these thread took longer than main method?
The main function will finish, and the JVM will block until the threads complete. Then the main thread will terminate.
Mike
+1  A: 
Runtime.getRuntime().exec(new String[]{"cmd","/c","java -jar app1.jar"});
Runtime.getRuntime().exec(new String[]{"cmd","/c","java -jar app2.jar"});

Just use Runtime execute service, if you don't call process.waitFor() to get return code of process, it won't blocking, so you can call next app immediately. If you want return code from app, run app on each Thread as Mike.

secmask
could you explain me when it will block and when it will not block...i want to execute .bat which will start another batch. can i do the same and it will not block. plz explain as i am new on this.
When you create a new child process by using Runtime.exec(...), it return a process object, if you want to know child process return code, you have to wait for it util it exit, to do this, just call waitFor() with process object you've received. waitFor() will cause your thread, which call this method block util child process end. You have 2 app that independence to each other, if you needn't listen to exit code of these, just don't call waitFor(), you won't be block, and can call next exec immediately by then.
secmask