I was going through an Apache Procrun tutorial and came across the following implementation for the start and stop methods of the service.
public static void start(String[] args) {
startThread();
synchronized (loggerThread) {
try {
loggerThread.wait();
} catch (InterruptedException e) {
log("'Wait' interrupted: " + e.getMessage());
}
}
}
public static void stop(String[] args) {
if (loggerThread != null) {
log("Stopping the thread");
loggerThread.interrupt();
synchronized (loggerThread) {
loggerThread.notify();
}
} else {
log("No thread to interrupt");
}
}
private static void startThread() {
log("Starting the thread");
loggerThread = new Thread(new RandomLoggerService());
loggerThread.start();
}
When the start method is called, it calls the "startThread" method which will create a new thread and whatever is in its "run" method implementation would start executing. But why is the "loggerThread" synchronized on and why is it put to wait? And when I call the stop method it should notify the wait in start method right. So why is the execution logic handed over to start method again by the stop method? This is a little confusing, Please advice.