Priority of a Thread (Thread Priority)in Java

Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads are scheduled. The threads with higher priority will usually run before and/or more frequently than lower priority threads. By default, all the threads had the same priority i.e. they are regarded as being equally important by the scheduler, when a thread is created it inherits its priority from the thread that created it. However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority () method. This method accepts an argument of type in t that defines the new priority of the thread. Its

syntax is.
final void setPriority(int priority)

Here, priority is an integer value that must range between 1 and 10, with 10 being the highest priority, 1 being the lowest and 5 being the default. If you specify a priority that is out of range then an IllegalArgumentException exception will be thrown. Some thread priorities are static member variables of java.lang .

3 constants defined in Thread class:
  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.

Example of priority of a Thread:
class Test 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[]){ Test m1=new Test(); Test m2=new Test(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } }


Output:
running thread name is:Thread-1 running thread priority is:10 running thread name is:Thread-0 running thread priority is:1



Instagram