user1414413
user1414413

Reputation: 403

how do I wait for process to complete

I am a c++ engineer so please be gentle!! I have some Java code that starts a process, but I want to do is halt execution until the new process completes.

How do I do this in Java?

Thanks

Upvotes: 0

Views: 765

Answers (4)

Mehdi MAHDAOUI
Mehdi MAHDAOUI

Reputation: 11

If I am right, you are trying to synchronize processes (Threads).

If for example, you want to wait for completion of your thread t1 before resuming your main process here is an idea:

Thread t1 = new MyThreadExample();
t1.start();
t1.join(); //wait for completion
/*
  write what you want to do after completion

*/

Upvotes: 0

Dyapa Srikanth
Dyapa Srikanth

Reputation: 1241

Read the stream from Process. It will wait for process completion before executing remaining code.

Process p = Runtime.getRuntime().exec("your command(process)", null, new File("path of process where to execute"));
    InputStream is=p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line = reader.readLine();
    while (line != null) {
      line = reader.readLine();
    }

Upvotes: 0

Bozho
Bozho

Reputation: 597106

If a "process" is a java.lang.Process obtained by java.lang.Runtime, then use Process.waitFor()

Just for the sake of completeness: normally in Java, you work with threads, and the option to wait for a thread is to call thread.join()

Upvotes: 2

hmjd
hmjd

Reputation: 121971

Assuming you have a Process object that represents the newly created process use Process.waitFor(), which:

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

A Process object can be obtained from:

Upvotes: 4

Related Questions