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() and Thread.resume() have been deprecated:
Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.
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 extend SafeStoppableRunnable and call the method waitWhenStopped() 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.