Java Reference
In-Depth Information
priority for the default thread is
NORM_PRIORITY
. The priority of a run-
ning thread can be changed at any time. If you assign a thread a pri-
ority lower than its current one, the system may let another thread run
because the original thread may no longer be among those with the
highest priority. The
getPriority
method returns the priority of a thread.
Generally, if you are to worry about priorities at all, the continuously
running part of your application should run in a lower-priority thread
than the thread dealing with rarer events such as user input. When
users push a "Cancel" button, for example, they expect the application
to cancel what it's doing. If display update and user input are at the
same priority and the display is updating, considerable time may pass
before the user input thread reacts to the button. If you put the display
thread at a lower priority, it will still run most of the time because the
user interface thread will be blocked waiting for user input. When user
input is available, the user interface thread will typically preempt the
display thread to act on the user's request. For this reason, a thread that
does continual updates is often set to
NORM_PRIORITY-1
so that it doesn't
hog all available cycles, while a user interface thread is often set to
NORM_PRIORITY+1
.
Using small "delta" values around the normal priority level is usually
preferable to using
MIN_PRIORITY
or
MAX_PRIORITY
directly. Exactly what ef-
fect priorities have depends on the system you are running on. In some
systems your thread priorities not only assign an importance relative
to your program, they assign an importance relative to other applica-
undesirable behavior and so should be avoided unless their effects are
known and needed.
[1]
Check the release notes for your virtual-machine implementation; some implementations treat
ranges of priority values as the same, thus reducing the number of distinct scheduling classes.
Some algorithms are sensitive to the number of processors available to
the virtual machine to run threads on. For example, an algorithm might
split work up into smaller chunks to take advantage of more parallel pro-
cessing power. The
availableProcessors
method of the
Runtime
class (see
Chapter 23
)
returns the number of processors currently available. Note