Java Reference
In-Depth Information
This gives other threads of the same priority the opportunity to run.
If each iteration of the loop takes a significant amount of time, you may want to inter‐
sperse more calls to Thread.yield() in the rest of the code. This precaution should
have minimal effect in the event that yielding isn't necessary.
Sleeping
Sleeping is a more powerful form of yielding. Whereas yielding indicates only that a
thread is willing to pause and let other equal-priority threads have a turn, a thread that
goes to sleep will pause whether any other thread is ready to run or not. This gives an
opportunity to run not only to other threads of the same priority, but also to threads of
lower priorities. However, a thread that goes to sleep does hold onto all the locks it's
grabbed. Consequently, other threads that need the same locks will be blocked even if
the CPU is available. Therefore, try to avoid sleeping threads inside a synchronized
method or block.
A thread goes to sleep by invoking one of two overloaded static Thread.sleep() meth‐
ods. The first takes the number of milliseconds to sleep as an argument. The second
takes both the number of milliseconds and the number of nanoseconds:
public static void sleep ( long milliseconds ) throws InterruptedException
public static void sleep ( long milliseconds , int nanoseconds )
throws InterruptedException
Although most modern computer clocks have at least close-to-millisecond accuracy,
nanosecond accuracy is rarer. There's no guarantee that you can actually time the sleep
to within a nanosecond or even within a millisecond on any particular virtual machine.
If the local hardware can't support that level of accuracy, the sleep time is simply rounded
to the nearest value that can be measured. For example, this run() method attempts to
load a certain page every five minutes and, if it fails, emails the webmaster to alert him
of the problem:
public void run () {
while ( true ) {
if (! getPage ( "http://www.ibiblio.org/" )) {
mailError ( "webmaster@ibiblio.org" );
}
try {
Thread . sleep ( 300000 ); // 300,000 milliseconds == 5 minutes
} catch ( InterruptedException ex ) {
break ;
}
}
}
The thread is not guaranteed to sleep as long as it wants to. On occasion, the thread may
not wake up until some time after its requested wake-up call, simply because the VM is
busy doing other things. It is also possible that some other thread will do something to
Search WWH ::




Custom Search