img
. . .
doWork();
ExitThread(status);
}
Exiting a Thread
Conversely, a thread is exited by calling the appropriate thread exit function or simply returning
from the initial function. Beyond the actual call to the create function, there is no parent/child
relationship--any thread can create as many threads as it pleases and, after creation, there will be
no relationship between the creator and createe.
In Java there is no thread exit function as there is in the other libraries, and the only way of exiting
a thread is to return from the run() method. This seems a bit odd, but it is intentional. The basic
idea is that only the run() method should make the decision to exit. Other methods lower in the
call chain may decide that they are done with what they are doing, or they may encounter an error
condition, but all they should do is pass that information up the call stack. They may return unique
values to indicate completion or they may propagate an exception, but they shouldn't exit the
thread.[1]
[1]
In earlier programs we looked at this differently and even wrote a "thread exit" function for Java
using thread.stop(). We recommend not doing that.
Moreover, even the run() method shouldn't be exiting the thread explicitly because it doesn't
"know" that it's running in a unique thread. It is perfectly reasonable for a program to call the
run() method in a new thread sometimes, and from an existing thread other times.
The Runnable Interface
There is a second method of creating a Java thread. In this method you write a class that
implements the Runnable interface, defining a run()method on it (Figure 4-1). You then create
a thread object with this runnable as the argument and call start() on the thread object. In
simple examples, either method is fine, but we'll soon discover that the latter method is superior,
and we'll use it in all our code (see Code Example 4-4). You will probably never use the first
method yourself.
Example 4-4 Simple Call to Run a Runnable in a Thread
public MyRunnable implements Runnable {
public void run(){
doWork();
}
}
Runnable r = new MyRunnable()
Thread t = new Thread(r);
t.start();
Figure 4-1. Creating a Thread via a Runnable
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home