group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
270 Members
Join this group to post and comment.
DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
10 Feb 2019

What is the priority of a thread in java?

As we know, Java allows multithreaded programming. i.e Java application can have more than one threads running simultaneously. When an application has multiple threads they are choosen to execute on priority basis. A thread with highest priority is choosen first for execution than the thread with lowest priority.

There are two methods in java.lang.Thread class related to priority of a thread. They are setPriority() and getPriority methods. setPriority() method is used to set the priority of a thread and getPriority() method is used to retrieve the priority of a thread. Below is the method signatures of these methods.

public final void setPriority(int newPriority)  —> Changes the priority of a thread to newPriority.

public final int getPriority()  —>  Returns the priority of a thread.

There are three constant fields in java.lang.Thread class related to priority of a thread. They are,

MIN_PRIORITY   —> It defines the lowest priority that a thread can have and It’s value is 1.

NORM_PRIORITY  —> It defines the normal priority that a thread can have and it’s value is 5.

MAX_PRIORITY  —> It defines the highest priority that a thread can have and it’s value is 10.

The setPriority() method may throw two exceptions. One is IllegelArgumentException if supplied priority is not in the range of MIN_PRIORITY and MAX_PRIORITY and another one is SecurityException if current thread can not modify the priority of a specified thread.

The priority of a main thread, if explicitly not set, is always 5 i.e NORM_PRIORITY.

The default priority of a thread is same as that of it’s parent.

Shruthi Pillai
Shruthi Pillai
Information Technology
3mos ago

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority  .

3 constants defined in thread class are :

  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

class TestMultiPriority1 extends Thread{  

public void run(){  

  System.out.println("running thread name is:"+Thread.currentThread().getName());  

  System.out.println("running thread priority is:"+Thread.currentThread().getPriority());  

   }  

 public static void main(String args[]){  

  TestMultiPriority1 q1=new TestMultiPriority1();  

  TestMultiPriority1 q2=new TestMultiPriority1();  

  q1.setPriority(Thread.MIN_PRIORITY);  

  q2.setPriority(Thread.MAX_PRIORITY);  

  q1.start();  

  q2.start();  

    }  

}