I assume you were confused by the wait()
method name, thinking it may allow you to wait until exec()
is finished, but really it's not and has completely different purpose.
What I believe you wanted here is to call Process.waitFor()
method:
try {
Runtime runtime = Runtime.getRuntime();
String cmd = new String(C:\\abc.bat);
process = runtime.exec("\"" + cmd + "\"");
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
which should do what you may originally expected — to wait until batch execution is finished.
On the other hand, wait()
method in Java (which comes from Object.wait()
) is related to multi-threading programming and to Java implementation of the monitor thread synchronization concept. Historically, it was put to the main Object.java
class, so all classes inherit it and that's what confusion may come from.
In your example it's definitely not the right method to call. And the IllegalStateMonitor
exception message you're getting:
current thread is not owner
tries to give you an implicit hint on threads synchronization issue.
Though again, when you're not using multi-threading in your code it may confuse you a lot and doesn't provide any clue what could go wrong, as you not expecting it.
wait()
method should only be called on the monitor objects, when you're writing code inside of synchronized blocks or methods, e.g.:
private final List<Task> tasks = new ArraList<>();
private synchronized void waitForTasks() throws InterruptedException {
// because 'synchronized' word used on method,
// here monitor is the whole class, i.e. 'this'
if (tasks.isEmpty()) {
wait(); // method is called on the class itself, as it's the monitor object
}
doTasks();
}
or:
private final List<Task> tasks = new ArraList<>();
private void waitForTasks() throws InterruptedException {
synchronized (tasks) { // monitor object is set to 'tasks' object
if (tasks.isEmpty()) {
tasks.wait(); // method is called on the monitor
}
doTasks();
}
}
If you would like to get more information on monitor concept in Java, you can this nice article on the topic.