I want to make a method that safely stops a thread running in a loop, allowing for the last loop to finish before returning control to the stopper.
Right now, no matter what I try, I freeze. Possibly out of deadlocks or whatnot; Java is not my usual environment, hence why this may be yet-another wait/notify question.
boolean isRunning = true;
@Override
public void run() {
super.run();
while (isRunning) {
// Do work...
}
synchronized(this) {
this.notify();
}
}
public void stopSafely() {
isRunning = false;
try {
synchronized(this) {
this.wait();
}
} catch (InterruptedException ex) {
// Handle...
}
}
The problem with this approach (apart from the fact that I synchronize on this, but it’s for the sake of example simplicity), is that if notify gets called before wait, the caller will freeze.
I’m sure that playing with the blocks I surround in synchronized could fix the problem, but I can’t seem to get the right combination.
Any idea?
Just go for the real simple solution:
that’s basically what
Thread.interrupted()does internally, so you can just use this as well:in which case you have to call
interrupt()on the thread.