Java Reference
In-Depth Information
If this is not precise enough, you have a version of
join()
with two parameters. The first is a time in milli-
seconds and the second is a time in nanoseconds. The current thread waits for the duration specified by the
sum of the arguments. Of course, whether or not you get nanosecond resolution depends on the capability of
your hardware.
The
join()
method can throw an
InterruptedException
if the current thread is interrupted by another
thread, so you should put a call to
join()
in a
try
block and catch the exception.
Thread Scheduling
The scheduling of threads depends to some extent on your operating system, but each thread certainly gets
a chance to execute while the others are “asleep," that is, when they've called their
sleep()
methods. If
your operating system uses preemptive multitasking (Microsoft Windows and Linux both support preempt-
ive multitasking), or your hardware has multiple processors that are supported by the operating system, the
program works without the call to
sleep()
in the
run()
method (you should also remove the
try
and
catch
blocks if you remove the
sleep()
call). However, if your operating system doesn't schedule in this way,
without the
sleep()
call in
run()
, the
first
thread hogs a single processor and continues indefinitely.
Figure 16-5
illustrates how four threads might share a single processor over time by calling the
sleep()
method to relinquish control.
Note that there's another method,
yield()
, defined in the
Thread
class, that gives other threads a chance
to execute. You use this when you just want to allow other threads a look-in if they are waiting, but you don't
want to suspend execution of the current thread for a specific period of time. When you call the
sleep()
method for a thread, the thread does not continue for at least the time you have specified as an argument,
even if no other threads are waiting. Calling
yield()
, on the other hand, causes the current thread to resume
immediately if no threads are waiting.
Implementing the Runnable Interface