Java Reference
In-Depth Information
assigns a worker to service each client that connects to it. When the client signs
off, the threaded worker process assigned to it dies.
8.3 Stopping threads
A thread dies in three ways:
it returns from run()
the stop() method is invoked (this method is now deprecated)
it is interrupted by a runtime exception
The first approach is always the preferred way for a thread to die. In the examples
shown above in Section 8.2, we used a flag variable in a loop to tell the run method
to finish. We recommend this approach to killing a thread.
Do not use the Thread method stop() to kill a thread. The stop() method
has been deprecated . That means that it still exists in the class definition but is
officially marked as obsolete and should be avoided. The stop() method causes
the thread to cease whatever it is doing and to throw a ThreadDeath exception.
This can leave data in an unknown state. For example, the thread might be midway
through setting the values of a group of variables when the thread was stopped.
This will leave some variables with new values and some with old values. Other
processes using those variables might then obtain invalid results. Furthermore, an
instruction involving a long or double type value can require two operations
in the JVM, which moves data in 32-bit chunks. So a thread stop might occur
after the first operation and leave the value in an indeterminate state. These kinds
of errors will be difficult to track down since the effect may not be seen until the
processing reaches another part of the program.
As mentioned earlier, the best way to stop a thread is to signal that the pro-
cessing should return from run() . Setting a flag can usually accomplish this. A
loop can check the flag after each pass and escape from the loop with the flag
switches. This allows for the process to finish what it is doing in a controlled
manner. In previous examples we set a boolean flag. In the applet below we use
the thread reference instead of a separate flag variable. Setting the reference to
null signals for the end of a loop in run() and also allows the garbage collector
to reclaim the memory used by the thread.
public class MyApplet extends Applet implements Runnable
{
Thread fMyThread;
public void init () {
...
 
Search WWH ::




Custom Search