img
. .
public class InterruptibleThread extends Thread {
public static void exit() {
Thread.currentThread().stop();
}
...
For a long time in our programs we simply put a little syntactic sugar over it and included it in our
InterruptibleThread class as below. You will find examples of code like this in many of
our older example programs. We have subsequently been convinced that this is the wrong way to
do things. Indeed, we have been convinced that even pthread_exit() is the wrong way to do
things!
Never Exit a Thread!
More accurately, never try to exit a thread explicitly. The argument goes like this: A runnable
should be viewed as a package of work to be done. As such, you never know for sure just who is
going to do that work. It could be a new thread, it could be an old thread, it could be the current
thread. As such, neither the run() method nor any of the methods it calls (most certainly not any
library objects you bought from Joe's Object Factory) should cause a thread to exit. They don't
know anything about the thread that's running them.
If there is a problem, they should either deal with it directly or throw an exception to be handled
by a higher-level method. The run method itself has no idea which thread is running it, so at most
it should simply return. If returning happens to exit the thread running it, that's OK. This way,
runnable objects are free to be used by any thread in any fashion it chooses.
In our ThreadedSwing example (Code Example 9-4; see also Threads and Windows), we do
exactly this. In the snippet below, when we run the program with threads turned off, the work is
performed by the current thread in-line. When we turn threads on, the work is farmed out to a new
thread.
Don't Call destroy()
There is another method, destroy() which stops a thread but doesn't unlock locks or run
finally sections. It was intended as a thread killer of last resort (in case you were in an
unstoppable loop or if there were a bug in the JVM). If you use this method to kill a thread, you
should expect the rest of your program to either crash or hang sooner or later. This method is not
deprecated in Java 2, but neither is it implemented in any of the JVMs.
Example 9-4 From ThreadedSwing Example: NumericButtonListener.java
public void actionPerformed(ActionEvent event) {
ThreadedJButton currentButton =
(ThreadedJButton)event.getSource();
System.out.println("Pressed " + currentButton);
currentButton.setEnabled(false);
System.out.println(currentButton + " disabled.");
DoWorker w = new DoWorker(currentButton);
if (ThreadedSwing.useThreads)
new Thread(w).start();
else
w.run();
}
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home