Java Reference
In-Depth Information
You can also pass a
long
value to the
join()
method to specify the number of milliseconds you're
prepared to wait for the death of a thread:
thread1.join(1000); // Wait up to 1 second for thread1 to die
If this is not precise enough, there is a version of
join()
with two parameters. The first is a time in
milliseconds and the second is a time in nanoseconds. The current thread will wait for the duration
specified by the sum of the arguments. Of course, whether or not you get nanosecond resolution will
depend 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 will
certainly get 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, as Windows 98 does, the
program will work 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 will hog the processor, and
will continue indefinitely.
The diagram below illustrates how four threads might share the processor over time by calling the
sleep()
method to relinquish control.
thread1
thread2
thread3
thread4
thread1
sleep()
thread2
sleep()
thread3
sleep()
time
thread4
sleep()
thread1
sleep()
The shaded areas indicate when each thread is executing
Note that there's another method,
yield()
, defined in the
Thread
class, that gives other threads a
chance to execute. You would 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 will 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
will cause the current thread to resume immediately if no threads are waiting.