1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| /**
* Detects when a process is finished and invokes the associated listeners.
*/
public class ProcessExitDetector extends Thread {
/** The process for which we have to detect the end. */
private Process process;
/** The associated listeners to be invoked at the end of the process. */
private List<ProcessListener> listeners = new ArrayList<ProcessListener>();
/**
* Starts the detection for the given process
* @param process the process for which we have to detect when it is finished
*/
public ProcessExitDetector(Process process) {
try {
// test if the process is finished
process.exitValue();
throw new IllegalArgumentException("The process is already ended");
} catch (IllegalThreadStateException exc) {
this.process = process;
}
}
/** @return the process that it is watched by this detector. */
public Process getProcess() {
return process;
}
public void run() {
try {
// wait for the process to finish
process.waitFor();
// invokes the listeners
for (ProcessListener listener : listeners) {
listener.processFinished(process);
}
} catch (InterruptedException e) {
}
}
/** Adds a process listener.
* @param listener the listener to be added
*/
public void addProcessListener(ProcessListener listener) {
listeners.add(listener);
}
/** Removes a process listener.
* @param listener the listener to be removed
*/
public void removeProcessListener(ProcessListener listener) {
listeners.remove(listener);
}
}
The code is very easy to understand. It creates a class as the detector for the process exit. It has a process to watch for passed in as a constructor argument. The entire thread does nothing else than wait for the given process to finish and then invokes the listeners.
The code for the ProcessListener is as easy:
1
2
3
public interface ProcessListener extends EventListener {
void processFinished(Process process);
}
Now you have a very easy way to detect when a subprocess is finished, and as proof, here is a code sample:
1
2
3
4
5
6
7
8
9
// ...
processExitDetector = new ProcessExitDetector(subprocess);
processExitDetector .addProcessListener(new ProcessListener() {
public void processFinished(Process process) {
System.out.println("The subprocess has finished.");
}
});
processExitDetector.start();
// ...
. |
Partager