Java - Thread Thread Priority

Introduction

All threads have a priority which is indicated by an integer between 1 and 10.

A thread priority of 1 is the lowest priority and 10 is the highest priority.

There are three constants defined in the Thread class to represent three different thread priorities.

Thread Priority ConstantsInteger Value
MIN_PRIORITY 1
NORM_PRIORITY5
MAX_PRIORITY 10

The priority of a thread is a hint to the scheduler, just a hint.

The higher priority of a thread the more chance a thread would get the CPU time.

setPriority() method of the Thread class sets a new priority for the thread.

getPriority() method returns the current priority for a thread.

When a thread is created, its priority is set to the priority of the thread that creates it.

The following code sets and gets the priority of a thread.

Demo

public class Main {
  public static void main(String[] args) {
    // Get the reference of the current thread
    Thread t = Thread.currentThread();
    System.out.println("main Thread Priority:" + t.getPriority());

    // Thread t1 gets the same priority as the main thread at this point
    Thread t1 = new Thread();
    System.out.println("Thread(t1) Priority:" + t1.getPriority());

    t.setPriority(Thread.MAX_PRIORITY);
    System.out.println("main Thread Priority:" + t.getPriority());

    // Thread t2 gets the same priority as main thread at this point, which is
    // Thread.MAX_PRIORITY (10)
    Thread t2 = new Thread();
    System.out.println("Thread(t2) Priority:" + t2.getPriority());

    // Change thread t2 priority to minimum
    t2.setPriority(Thread.MIN_PRIORITY);
    System.out.println("Thread(t2) Priority:" + t2.getPriority());
  }/*w  ww  .  ja  v  a 2s.c  o  m*/
}

Result