Thread Priority in Java

In Java every thread has some priority, this priority can be default provided by JVM or customized priority provided by the programmer. The range of priority in Java is 1 to 10, where 1 is min priority and 10 is a maxed priority.

Thread class defines the following constants to represent standard priorities.

Thread.MIN_PRIORITY  //1
Thread.MAX_PRIORITY  //10
Thread.NORM_PRIORITY  //5

The thread scheduler uses these priorities while allocating resources, Thread having the highest priority will get a chance first.

If two Threads have the same priority then we can’t expect the exact execution order, In this scenario execution order depends upon the thread scheduler.

Getting and Setting priority of Thread

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

public final int getPriority() 
public final void setPriority(int priority)

An example of a Java program for getting and setting the priority of Thread.

public class ThreadName extends Thread {


}
   class ThreadNameDemo {
       public static void main(String[] args) {
           ThreadName object = new ThreadName();
           System.out.println(object.getPriority());
           object.setPriority(8);
           System.out.println(object.getPriority());
       }
       }
Getting and Setting priority of Thread

Default Priority for Threads in Java

The default priority for the main Thread is 5. For all other threads default priority will be inherited from parent to child that is whatever priority patient Thread has the same priority will be there for child Thread.

public class ThreadName extends Thread {


}
   class ThreadNameDemo {
       public static void main(String[] args) {
           ThreadName object = new ThreadName();
           System.out.println(Thread.currentThread().getPriority());
           System.out.println(object.getPriority());
       }
       }
Default Priority for Threads in Java

Similar Java Tutorials