Java Reference
In-Depth Information
wake up the sleeping thread before its time. Generally, this is accomplished by invoking
the sleeping thread's
interrupt()
method.
public
void
interrupt
()
This is one of those cases where the distinction between the thread and the
Thread
object
is important. Just because the thread is sleeping doesn't mean that other threads that are
awake can't work with the corresponding
Thread
object through its methods and fields.
In particular, another thread can invoke the sleeping
Thread
object's
interrupt()
method, which the sleeping thread experiences as an
InterruptedException
. From
that point forward, the thread is awake and executes as normal, at least until it goes to
sleep again. In the previous example, an
InterruptedException
is used to terminate a
thread that would otherwise run forever. When the
InterruptedException
is thrown,
the infinite loop is broken, the
run()
method finishes, and the thread dies. The user-
interface thread can invoke this thread's
interrupt()
method when the user selects Exit
from a menu or otherwise indicates that he wants the program to quit.
If a thread is blocked on an I/O operation such as a read or write, the
effect of interrupting the thread is highly platform dependent. More
often than not, it is a noop. That is, the thread continues to be blocked.
On Solaris, the
read()
or
write()
method may throw an
Interrupte
dIOException
, a subclass of
IOException
instead. However, this is
unlikely to happen on other platforms, and may not work with all
stream classes on Solaris. If your program architecture requires inter‐
ruptible I/O, you should seriously consider using the nonblocking I/O
discussed in
Chapter 11
rather than streams. Unlike streams, buffers
and channels are explicitly designed to support interruption while
blocked on a read or write.
Joining threads
It's not uncommon for one thread to need the result of another thread. For example, a
web browser loading an HTML page in one thread might spawn a separate thread to
retrieve every image embedded in the page. If the
IMG
elements don't have
HEIGHT
and
WIDTH
attributes, the main thread might have to wait for all the images to load before it
can finish by displaying the page. Java provides three
join()
methods to allow one
thread to wait for another thread to finish before continuing. These are:
public
final
void
join
()
throws
InterruptedException
public
final
void
join
(
long
milliseconds
)
throws
InterruptedException
public
final
void
join
(
long
milliseconds
,
int
nanoseconds
)
throws
InterruptedException
The first variant waits indefinitely for the
joined
thread to finish. The second two var‐
iants wait for the specified amount of time, after which they continue even if the joined