Java Reference
In-Depth Information
Not all operating systems support 11 different priorities. For in‐
stance, Windows only has 7. On Windows, priorities 1 and 2, 3 and 4,
6 and 7, and 8 and 9 are treated equally (e.g., a priority 9 thread will
not necessarily preempt a priority 8 thread).
Sometimes you want to give one thread more time than another. Threads that interact
with the user should get very high priorities so that perceived responsiveness will be
very quick. On the other hand, threads that calculate in the background should get low
priorities. Tasks that will complete quickly should have high priorities. Tasks that take
a long time should have low priorities so that they won't get in the way of other tasks.
You can change the priority of the thread using the setPriority() method:
public final void setPriority ( int newPriority )
Attempting to exceed the maximum priority or set a nonpositive priority throws an
IllegalArgumentException .
For instance, in Example 3-11 , you might want to give higher priorities to the threads
that do the calculating than the main program that spawns the threads. This is easily
achieved by changing the calculateDigest() method to set the priority of each
spawned thread to 8:
public void calculateDigest () {
ListCallbackDigest cb = new ListCallbackDigest ( filename );
cb . addDigestListener ( this );
Thread t = new Thread ( cb );
t . setPriority ( 8 );
t . start ();
}
In general, though, try to avoid using too high a priority for threads, because you run
the risk of starving other, lower-priority threads.
Preemption
Every virtual machine has a thread scheduler that determines which thread to run at
any given time. There are two main kinds of thread scheduling: preemptive and coop‐
erative . A preemptive thread scheduler determines when a thread has had its fair share
of CPU time, pauses that thread, and then hands off control of the CPU to a different
thread. A cooperative thread scheduler waits for the running thread to pause itself before
handing off control of the CPU to a different thread. A virtual machine that uses co‐
operative thread scheduling is much more susceptible to thread starvation than a virtual
machine that uses preemptive thread scheduling, because one high-priority, uncooper‐
ative thread can hog an entire CPU.
All Java virtual machines are guaranteed to use preemptive thread scheduling between
priorities. That is, if a lower-priority thread is running when a higher-priority thread
Search WWH ::




Custom Search