Java Thread Priority Example

In this article, we will learn how to priorities threads in a Java application.
Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. 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.

setPriority(int newPriority) Method Overview

  • setPriority(int newPriority) - changes the priority of this thread.
First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.
Otherwise, the priority of this thread is set to the smaller of the specified newPriority and the maximum permitted priority of the thread's thread group.
Parameters: newPriority priority to set this thread to.
Throws:  IllegalArgumentException - If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY. SecurityException - if the current thread cannot modify this thread.

Set Priority to a Thread Example

public class ThreadPriorityExample {
     public static void main(final String[] args) {
          final Runnable runnable = () -> {
               System.out.println("Running thread name : " + Thread.currentThread().getName() +  
               " and it's priority : " + Thread.currentThread().getPriority());
   
          };
  
          final Thread thread1 = new Thread(runnable);
          final Thread thread2 = new Thread(runnable);
          final Thread thread3 = new Thread(runnable);
          final Thread thread4 = new Thread(runnable);
          thread1.setPriority(Thread.MIN_PRIORITY);
          thread2.setPriority(Thread.NORM_PRIORITY);
          thread3.setPriority(Thread.MAX_PRIORITY);
          thread4.setPriority(2);
  
          thread1.start();
          thread2.start();
          thread3.start();
          thread4.start();
     }
}
Output:
Running thread name : Thread-0 and it's priority : 1
Running thread name : Thread-1 and it's priority : 5
Running thread name : Thread-2 and it's priority : 10
Running thread name : Thread-3 and it's priority : 2

Comments