Thread Priority in Java

In a multi-threaded environment, the order in which threads will get CPU cycle is decided by the thread scheduler and it uses thread priority to decide that order. Though that doesn’t mean that the low priority threads will never get a chance to run, that is thread priority in Java won’t lead to a deadlock but low priority threads will get fewer CPU cycles. Higher priority thread can also preempt a lower-priority thread.

Java thread priority

Every thread in Java has a priority assigned to it. When you create a thread in Java it inherits the priority of the thread that created it. You can change thread’s priority at any time after its creation using the setPriority() method of the Thread class. If you want to check the thread’s priority you can check it using getPriority() method of the Thread class.

  • setPriority(int newPriority) – Changes the priority of this thread. Here newPriority is the priority to set this thread to. If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY, IllegalArgumentException is thrown.
  • getPriority()– Returns the priority of the thread that has called this method.

Java thread priority is in the range 1 to 10 where 1 being the lowest and 10 being the highest thread priority in Java.

In Java Thread class there are three static int fields defining min, max and default priority of a thread.

  • MAX_PRIORITY– The maximum priority that a thread can have. Its value is 10.
  • MIN_PRIORITY– The minimum priority that a thread can have. Value of this field is 1.
  • NORM_PRIORITY– The default priority that is assigned to a thread. Its value is 5.

Java thread priority example

Here is an example program showing the thread priorities in Java. Three threads are created here and initially the original priority of those threads is displayed using the getPriority() method then the priority is changed using the setPriority() method.

Output

You can see in the output that the thread with the highest priority is executed first. But that may not always be the case and you may get different output too as the platform Java is running on is also one of the factor as that platform may have a different implementation for multi-tasking.

Thread priority is platform dependent

The platform, Java is running on may have different priority levels for threads resulting in more or less priority levels than the thread priority level in Java. In that case JVM tries to map the Java thread priority to the priority level of the OS.

That’s all for the topic Thread Priority in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: Main Thread in Java - KnpCode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.