Java - Thread Thread Priority


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

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.


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

    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
    System.out.println("Thread(t2) Priority:" + t2.getPriority());
  }/*  w w w . j ava2  s. c o m*/