Minimum and Maximum Priority Threads in Java


The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread.

There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY. The values of these variables are 1, 10 and 5 respectively.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class ThreadDemo extends Thread {
   public void run() {
      System.out.println("Running...");
   }
   public static void main(String[] args) {
      ThreadDemo thread1 = new ThreadDemo();
      ThreadDemo thread2 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      thread1.setPriority(MAX_PRIORITY);
      thread2.setPriority(MIN_PRIORITY);
      System.out.println("
The maximum thread priority of Thread 1 is: " + thread1.getPriority());       System.out.println("The minimum thread priority of Thread 2 is: " + thread2.getPriority());       System.out.println("
" + Thread.currentThread().getName());       System.out.println("Default thread priority of Main Thread: " + Thread.currentThread().getPriority());       Thread.currentThread().setPriority(MAX_PRIORITY);       System.out.println("The maximum thread priority of Main Thread is: " + Thread.currentThread().getPriority());    } }

Output

Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
The maximum thread priority of Thread 1 is: 10
The minimum thread priority of Thread 2 is: 1
main
Default thread priority of Main Thread: 5
The maximum thread priority of Main Thread is: 10

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements