posted 23 years ago
Actually the thread will not be GC'd as long as it is running, even if all other references in the program are deleted. This is because the way GC is defined, an object my be deleted only if there is no way to access it from any live thread. A live thread can always access itself; therefore it does not require that any other references to it exist in order to prevent garbage collection.
Also, in the last code example, it is important that all access to isRunning be from synchronized methods or blocks of code. Otherwise different threads may be using different, out-of-date copies of the isRunning value, without bothering to updateeach other. If this happens, setting isRunning to false may have no effect, since MyThread may never bother to get an updated value.
Typically, you also want to set up the code to check isRunning more than once while the thread is running. It depends on what the run() method is supposed to be doing in the first place, but usually if there's any sort of loop withing the run() method, you add (isRunning == true) to the list of conditions to continue the loop:
<code><pre>
class MyThread {
private boolean isRunning;
public synchronized boolean getIsRunning() {
return isRunning;
}
public sunchronized void setIsRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public void run() {
while (getIsRunning() && isThereMoreWorkToBeDone()) {
doSomeWork();
}
}
...
}</pre></code>
"I'm not back." - Bill Harding, Twister