Thread Priority

Every Thread in java has some priority but the range of thread priorities is 1 to 10 . (1 is least and 10 is highest ).
Thread class defines the following constants to define some standard priorities .
1) public static final int MIN_PRIORITY -> 1
2) public static final int NORM_PRIORITY -> 5
3) public static final int MAX_PRIORITY ->10


Default Priority

The default priority of main thread is 5 .
But for all the remaining threads , priority value is inherited from its parent i. e. whatever the priority parent has the same priority will be inheriting to the child thread.

  Thread class defines the following method to get and set the priority of a any thread .

  1) public final int getPriority() -it is used for getting the priority of thread.

  1) public final void setPriority(int priority) - for setting the priority of thread.
The allowed priority values are 1 to 10 , otherwise we will get IllegalArgumentException

Getting default priority


//example of getting the deafult priority of main thread
class PriorityTest
{
	public static void main(String[] args) {
		Thread t=Thread.currentThread();
		//getting the name of current running thread
		String currentThreadName=t.getName();
		//getting the priority 
		int currentThreadPriority=t.getPriority();
		//printing the name and priority
		System.out.println("default priority of "+currentThreadName+" is "+ currentThreadPriority);
	}
}
default priority of main is 5

Getting default priority of user thread(child thread).


//example of getting the default priority of userthread
class UserThread extends Thread
{
public void run()
{
 Thread ur=Thread.currentThread();
 System.out.println("My Name is :"+ur.getName());
 System.out.println("Priority of userthread is :"+ur.getPriority());

}
public static void main(String[] args) {
	System.out.println("Priority of Main thread is : "+ Thread.currentThread().getPriority());
	//changing the priority of main thread
	Thread.currentThread().setPriority(7);
	//printing again the priority of main thread
	System.out.println("Priority of Main thread is : "+ Thread.currentThread().getPriority());

	UserThread t=new UserThread();	
	t.start();
}
}
Priority of Main thread is : 5
Priority of Main thread is : 7
My Name is :Thread-0
Priority of userthread is :7