Java Reference
In-Depth Information
public static void sleepNow(long millis) {
try {
Thread.currentThread().sleep(millis);
}
catch (InterruptedException e) {
}
}
}
Before start()-ts.isAlive():false
#1:NEW
After start()-ts.isAlive():true
#2:RUNNABLE
#3:WAITING
#4:RUNNABLE
#5:TERMINATED
At the end. ts.isAlive():false
Priority of a Thread
All threads have a priority. The priority is indicated by an integer between 1 and 10. A thread with the priority
of 1 is said to have the lowest priority. A thread with the priority of 10 is said to have the highest priority. There are
three constants defined in the Thread class to represent three different thread priorities as listed in Table 6-4 .
Table 6-4. Thread's Priority Constants Defined in the Thread Class
Thread Priority Constants
Integer Value
MIN_PRIORITY
1
NORM_PRIORITY
5
MAX_PRIORITY
10
The priority of a thread is a hint to the scheduler that indicates the importance (or the urgency) with which it
should schedule the thread. The higher priority of a thread indicates that the thread is of higher importance and the
scheduler should give priority in giving the CPU time to that thread. Note that the priority of a thread is just a hint to
the scheduler; it is up to the scheduler to respect that hint. It is not recommended to depend on the thread priority
for the correctness of a program. For example, if there are ten maximum priority threads and one minimum priority
thread, that does not mean that the scheduler will schedule the minimum priority thread after all ten maximum
priority threads have been scheduled and finished. This scheduling scheme will result in a thread starvation , where a
lower priority thread will have to wait indefinitely or for a long time to get CPU time.
The setPriority() method of the Thread class sets a new priority for the thread. The getPriority() method
returns the current priority for a thread. When a thread is created, its priority is set to the priority of the thread that
creates it.
Listing 6-16 demonstrates how to set and get the priority of a thread. It also demonstrates how a new thread gets
the priority of the thread that creates it. In the example, threads t1 and t2 get the priority of the main thread at the
time they are created.
 
Search WWH ::




Custom Search