Computer >> Computer tutorials >  >> Programming >> Java

Java Thread Priority in Multithreading


In the situation of multi-threading, a thread scheduler assigns threads to specific processes based on their priority. A java thread comes with a pre-assigned priority. In addition to this, the java virtual machine can also assign priority to threads or explicitly given by the programmers. The range of values for the priority of a thread lie between 1 and 10 (inclusive). The three static variables associated with priority are −

  • MAX_PRIORITY − The maximum priority that a thread has, whose default value is 10.

  • NORM_PRIORITY − The default priority that a thread has, whose default value is 5.

  • MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1.

The ‘getPriority()’ method in Java helps in returning the priority of the thread bound as value to it.

The ‘setPriority()’ method changes the priority value of a given thread. It throws the IllegalArgumentException when the thread priority is less than 1 or greater than 10.

Example

import java.lang.*;
public class Demo extends Thread{
   public void run(){
      System.out.println("Now, inside the run method");
   }
   public static void main(String[]args){
      Demo my_thr_1 = new Demo();
      Demo my_thr_2 = new Demo();
      System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
      System.out.println("The thread priority of first thread is : " +       my_thr_2.getPriority());
      my_thr_1.setPriority(5);
      my_thr_2.setPriority(3);
      System.out.println("The thread priority of first thread is : " +    my_thr_1.getPriority());
      System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
      System.out.print(Thread.currentThread().getName());
      System.out.println("The thread priority of main thread is : " +
      Thread.currentThread().getPriority());
      Thread.currentThread().setPriority(10);
      System.out.println("The thread priority of main thread is : " +
      Thread.currentThread().getPriority());
   }
}

Output

The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 3
The thread priority of main thread is : 5
The thread priority of main thread is : 10

A class named Demo inherits from the base class Thread. The function ‘run’ is defined and a relevant message is defined. In the main function, two instances of the Demo class are created and their priorities are found by calling the function ‘getPriority’.

They are printed on the console. Next, the Demo instances are assigned priority by using the ‘setPriority’ function. The output is displayed on the console. The names of the threads are printed on the screen with the help of the ‘getName’ function.