Java Reference
In-Depth Information
As you can see, after the calls to join( ) return, the threads have stopped executing.
Thread Priorities
Each thread has associated with it a priority setting. A thread's priority determines, in part,
how much CPU time a thread receives relative to the other active threads. In general, over
a given period of time, low-priority threads receive little. High-priority threads receive a
lot. As you might expect, how much CPU time a thread receives has profound impact on
its execution characteristics and its interaction with other threads currently executing in the
system.
It is important to understand that factors other than a thread's priority also affect how
much CPU time a thread receives. For example, if a high-priority thread is waiting on some
resource, perhaps for keyboard input, then it will be blocked, and a lower priority thread
will run. However, when that high-priority thread gains access to the resource, it can pree-
mpt the low-priority thread and resume execution. Another factor that affects the schedul-
ing of threads is the way the operating system implements multitasking. (See “Ask the Ex-
pert” at the end of this section.) Thus, just because you give one thread a high priority and
another a low priority does not necessarily mean that one thread will run faster or more
often than the other. It's just that the high-priority thread has greater potential access to the
CPU.
When a child thread is started, its priority setting is equal to that of its parent thread. You
can change a thread's priority by calling setPriority( ) , which is a member of Thread . This
is its general form:
final void setPriority(int level )
Here, level specifies the new priority setting for the calling thread. The value of level must
be within the range MIN_PRIORITY and MAX_PRIORITY . Currently, these values are
1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY ,
which is currently 5. These priorities are defined as static final variables within Thread .
You can obtain the current priority setting by calling the getPriority( ) method of
Thread , shown here:
final int getPriority( )
The following example demonstrates two threads at different priorities. The threads are
created as instances of Priority . The run( ) method contains a loop that counts the number
of iterations. The loop stops when either the count reaches 10,000,000 or the static variable
stop is true . Initially, stop is set to false , but the first thread to finish counting sets stop to
Search WWH ::




Custom Search