. . . . . .
Finally, you can even use anonymous inner classes to define a thread's run() method (Code
Example 4-5). You could even create a thread and pass it an inner class runnable, but that seems
silly. We'll just define a run() method for the thread.
Example 4-5 Defining run() via an Inner Class in a Thread
new Thread() {
public void run() {
There are two reasons for using runnable. The first is that we are not changing the nature of the
thread itself, we're only changing the run() method, so subclassing Thread isn't really
appropriate. The second reason is that if we implement the Runnable interface, it's possible to
subclass something else more useful. (True, it's unlikely that you'll ever subclass anything for your
runnable; nonetheless, it's nice to have that option.) Still, the distinction between the two methods
is quite minor. There are a few cases where we will subclass Thread, but in none of those will we
ever define a run() method.
Moreover, we can consider a Runnable to be the work to be done, while the thread is the engine
to do the work. From this point of view, it makes no sense to include the work inside the engine.
On top of this, there is no reason to insist that the work be done in a unique thread. It is perfectly
reasonable to execute the run() method of a Runnable in the current thread. This is exactly
what we do in Threads and Windows.
What the run() method of Thread does by default is to look for a Runnable and call its run()
method. You could both subclass Thread and define a run() method on it and then pass it a
Runnable to run. In this case the run() method of the thread would be run. This would confuse
the heck out of anyone reading your code. Don't do that.
In Pthreads and Win32 each thread has a thread ID (TID), which may be used to control certain
aspects (scheduling classes, cancellation, signals, etc.) of that thread. (Win32 also defines a thread
handle, which is a different version of a TID.) In Java, all of this is more conveniently handled
simply by invoking methods on the thread object. (You will probably never call any methods on
the runnable yourself.)
Waiting for Threads
Sometimes you specifically want to wait for a thread to exit (see Figure 4-2 and Code Example 4-
6). Perhaps you've created 20 threads to do 20 pieces of a task, and you can't continue until they
are all finished. One method is to call the wait function (called join in Pthreads and Java) on each
of the desired threads. The caller will block until each of the specified threads has exited. The
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks