J2EEOnlineJ2EE





Java Multitasking  «Prev  Next»
Lesson 10Thread priorities
Objective Understand the concept behind and effect of thread priorities.

Concept behind Java Thread Priorities

With more than one thing happening at once, that is, with more than one thread, how does Java provide coordination among threads?
Java uses a fixed-priority scheduling algorithm. This means the execution of threads is based on their priorities.

Thread priorities Ladder
Thread priorities Ladder

You can think of the thread priorities as rungs on a ladder. The higher up the ladder, the higher the thread's priority. The thread with the highest priority sits on top of the ladder.
Java always runs the highest-priority thread. If another thread attains a higher priority, Java switches to start running that one (in other words, Java is preemptive); in that case, Java will make the lower-priority threads wait. If there is more than one thread with the same highest priority, standing on the same rung of the ladder, Java will switch between them quickly so that they all appear to be executing at once to the user.
Question: How does a thread get its priority?
Answer: When a thread is created, it takes its priority from the thread that created it. This way, threads run concurrently, with Java's scheduler switching back and forth between them.


You can also explicitly set a thread's priority higher or lower, as long as it falls within the range of
  1. MIN_PRIORITY and ,
  2. MAX_PRIORITY
values that the Thread class maintains. The default priority is midway between these two values.