img
. . . . .
other way is to use normal synchronization functions. (We'll talk about this in Using Barriers to
Count Exiting Threads .)
Example 4-6 Waiting for Threads to Exit
POSIX
Win32
Java
pthread_join(T5,...)
WaitForSingleObject(T5,...)
T5.join()
Figure 4-2. Using thread.join()
In addition to waiting for the threads to exit, the caller can receive a status from the exiting threads
in Win32 and POSIX. In Java there is no such concept, but it's easy enough to build an ad hoc
method should you need to. (You probably won't.) To ensure that no deadlocks occur, it makes no
difference if the waiting thread calls the join function first or if the exiting thread calls the exit
function first. Calling return() from the run method implicitly calls the thread exit function.
Obviously, you should join a thread only once. It is legal in Java to join a thread more than once,
but you're probably making a mistake if you do.
Who Am I?
Sometimes you want to know the identity of the current thread. In production programs this is
pretty rare; most commonly you just want to print out some debugging information about which
thread is running when. In any case, it's easy to do. All the libraries have a "current thread"
function (Code Example 4-7). In Java you may also wish to know which Runnable is being run.
You cannot find this out unless you build in a mechanism for it yourself (see Java TSD).
Example 4-7 Getting the Current Thread's Identity
POSIX
Win32
Java
pthread_self()
GetCurrentThread()
Thread.currentThread()
Don't Wait for Threads, Don't Return Status
When should you wait for a thread? Our opinion is never. Consider: Why do you care when a
thread exits? Because you are waiting for that thread to complete some task, the results of which
some other thread needs. By doing a join on that thread, you are implicitly assuming that the task
will be complete when the thread exits. Although this may indeed be true, it would be
conceptually cleaner if you simply waited for the task itself, using one of the synchronization
variables discussed in Chapter 6. In many of our examples we simply count the number of threads
that exit.
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home