Java Thread setPriority() Method Example

Java Thread Examples


This post describes the usage of the Java Thread setPriority() method with an example.

Java Thread setPriority() Method Overview

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the 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.
Three 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.

Java Thread setPriority() Method 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

Reference

Comments