The minimum thread priority in java is 1 and maximum or highest thread priority is 10. We will see a program example to set and get thread priority.
Default priority of thread in java is = 5.
Minimum thread Priority = 1
Maximum thread Priority = 10
We can set priority of a thread within this range only. If we set priority of thread other than this range then we will get an exception as IllegalArgumentException.
Every thread in java program has a priority. Threads with higher priority are executed in preference to threads with lower priority. When code running in some thread creates a new thread then the new thread has its priority initially set equal to the priority of the creating thread or parent thread.
Note that main application is also a thread and its default priority is always assigned to 5 when we create a program.
In java programming, following two methods are used to set priority of a thread and if we want to know the priority of a running thread then we can use getPriority() method
public final void setPriority(int newPriority) public final int getPriority()
How to set and get priority of a thread? Java code example
public class ThreadPriority { //Example to set thread priority public static void main(String[] args) throws InterruptedException { //Create 2 threads Thread threadoOne = new Thread(); Thread threadTwo = new Thread(); //Set the priority of both threads threadoOne.setPriority(Thread.MAX_PRIORITY); threadTwo.setPriority(Thread.MIN_PRIORITY); //Start threads threadoOne.start(); threadTwo.start(); //main thread will wait for both threads //to finish threadoOne.join(); threadTwo.join(); //get the thread priority of first thread int priority = threadoOne.getPriority(); System.out.println("thread priority of first thread is:"+priority); } }
Note that as we have set priority of first thread to maximum priority that is 10. If we use getPriority method to get the priority of thread output will be 10.