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);
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


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course