Java Reference
In-Depth Information
14.6. Thread Scheduling
Threads perform different tasks within your programs and those tasks
can have different importance levels attached to them. To reflect the im-
portance of the tasks they are performing, each thread has a priority that
is used by the runtime system to help determine which thread should be
running at any given time. Programs can be run on both single- and mul-
tiprocessor machines and you can run with multiple threads or a single
thread, so the thread scheduling guarantees are very general. On a sys-
tem with N available processors, you will usually see N of the highest-
priority runnable threads executing. Lower-priority threads generally run
only when higher-priority threads are blocked (not runnable). But lower-
priority threads might, in fact, run at other times to prevent starvationa
feature generally known as priority aging though you cannot rely on it.
A running thread continues to run until it performs a blocking operation
(such as wait , sleep , or some types of I/O) or it is preempted. A thread
can be preempted by a higher-priority thread becoming runnable or be-
cause the thread scheduler decides it's another thread's turn to get some
cyclesfor example, time slicing limits the amount of time a single thread
can run before being preempted.
Exactly when preemption can occur depends on the virtual machine you
have. There are no guarantees, only a general expectation that preferen-
ce is typically given to running higher-priority threads. Use priority only
to affect scheduling policy for efficiency. Do not rely on thread priority
for algorithm correctness. To write correct, cross-platform multithreaded
code you must assume that a thread could be preempted at any time,
and so you always protect access to shared resources. If you require that
preemption occur at some specific time, you must use explicit thread
communication mechanisms such as wait and notify . You also can make
no assumptions about the order in which locks are granted to threads,
nor the order in which waiting threads will receive notificationsthese are
all system dependent.
A thread's priority is initially the same as the priority of the thread that
created it. You can change the priority using setPriority with a value
between THRead 's constants MIN_PRIORITY and MAX_PRIORITY . The standard
 
Search WWH ::




Custom Search