Wednesday, October 17, 2007

Thread stop and suspend

Threads should not be stopped using stop or suspend. These methods are deprecated.

Instead, threads should use the following simple idiom to stop in a well behaved manner.

public final class SimpleThread implements Runnable {

public void run() {
boolean isDone = false;

while (!isStopRequested() && !isDone){
//perform the work
}
}

/**
* Request that this thread stop running.
*/
public synchronized void requestStop(){
fIsStopRequested = true;
}

// PRIVATE ////////

private boolean fIsStopRequested;

private synchronized boolean isStopRequested() {
return fIsStopRequested;
}
}

No comments: