Thread Priorities
Threads are assigned priorities that the thread scheduler can use to determine how the threads will be scheduled. The thread scheduler can use thread priorities to determine which thread gets to run. The thread scheduler favors giving CPU time to the thread with the highest priority in the READY substate. This is not necessarily the thread that has been in the READY substate the longest time. Heavy reliance on thread priorities for the behavior of a program can make the program unportable across platforms, as thread scheduling is host platform–dependent.
Selective priorities are defined by enum constants in the Thread class, shown in Table 22.2.
Table 22.2 Selective Priorities Defined by the Thread Class
Enum type java.lang.Thread | Value Description |
MIN_PRIORITY | 0 Lowest priority |
NORM_PRIORITY | 5 Default priority |
MAX_PRIORITY | 10 Highest priority |
A thread inherits the priority of its parent thread. The priority of a thread can be set using the setPriority() method and read using the getPriority() method, both of which are defined in the Thread class. The following code sets the priority of the thread myThread to the minimum of two values: maximum priority and current priority incremented to the next level. It also shows the default text representation of a thread, [thread_name, priority, parent_thread_name].
Thread myThread = new Thread(() ->
System.out.println(Thread.currentThread() + “: Don’t mess with my priority!”)
);
System.out.println(myThread);
myThread.setPriority(Math.min(Thread.MAX_PRIORITY, myThread.getPriority() + 1));
myThread.start();
Output from the code:
Thread[Thread-0,5,main]
Thread[Thread-0,6,main]: Don’t mess with my priority!
The setPriority() method is an advisory method, meaning that it provides a hint from the program to the JVM, which the JVM is in no way obliged to honor. A thread with higher priority is not guaranteed to complete its work faster than a thread with lower priority. The method can be used to fine-tune the performance of the program, but should not be relied upon for the correctness of the program.