Master java skills

Thread Priorities

Each thread in java has a priority. This priority is represented by a number in the range from 1-10. 1 being the least priority and 10 being the highest. Whereas the default or normal priority is 5.

Constants that define thread priorities

There are three constants defined in Thread class that represent thread priorities:

  1. Thread.MIN_PRIORITY – 1
  2. Thread.MAX_PRIORITY – 10
  3. Thread.NORM_PRIORITY – 5

By default, each thread is given a priority 5, which is represented by NORM_PRIORITY. But, it can be changed. We can assign any priority to a thread.

Note -> In preemptive scheduling, thread scheduler schedules threads based on their priorities. A higher priority thread is given more priority than a low priority thread.

Code Example to understand thread priorities

In the below example, we are going to create 2 threads. One thread will have default priority (5). For second thread, we will set the priority to max priority (10).

package com.javatrainingschool;

public class ThreadPriorityExample {

	public static void main(String[] args) {

                //creating thread using anonymous class
		Thread t1 = new Thread(new Runnable() {

			public void run() {
				System.out.println("Current Thread priority " + Thread.currentThread().getPriority());
			}
		});

		Thread t2 = new Thread(new Runnable() {

			public void run() {
				System.out.println("Current Thread priority " + Thread.currentThread().getPriority());
	}
		});

		t1.start();
		t2.start();
		t2.setPriority(Thread.MAX_PRIORITY);
	}
}
Output :
Current Thread priority 5
Current Thread priority 10