given a Runnable:
public class MyRunnable implements Runnable {
public void run() {
doA();
for (i=0; i<18123 ; i++) {
doB();
}
doC();
}
}
where doA,B,C are defined with like 100 lines of code each.
what is the best way to make the thread FREEZE – in whatever line of code its at – and then continue from the next line of code where it last stopped.
I was searching around the net, and I saw here http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
that they suggest on using a boolean, so, does that mean that i need to check that boolean after every few lines of code? there’s gotta be a nicer way…
That cannot work in general for the cause
Thread.suspend()andThread.resume()have been deprecated:If you absolutely need this behavior, you have to explicitly implemented it yourself.
The implementations could look like this (code not tested, nor compiled):
public abstract class SafeStoppableRunnable implements Runnable { private boolean stopped = false; public synchronized void stopSafe() { this.stopped = true; } public synchronized void resumeSafe() { this.stopped = false; synchronized(this) { this.notifyAll(); } } protected synchronized void waitWhenStopped() { while(this.stopped) { this.wait(); } } }The stoppable
Runnables should then extendSafeStoppableRunnableand call the methodwaitWhenStopped()at all the points in your program you want it to be stoppable. Stoppable points are probably points where the program does not hold global ressources other threads need to make progress.