Java Thread Priority
In the last chapter we have seen the ways of naming thread in java. In this chapter we will be learning the different priorities that a thread can have.
Contents
Java Thread Priority :
- Logically we can say that threads run simultaneously but practically its not true, only one Thread can run at a time in such a ways that user feels that concurrent environment.
- Fixed priority scheduling algorithm is used to select one thread for execution based on priority.
Example #1 : Default Thread Priority
getPriority() method is used to get the priority of the thread.
package com.c4learn.thread; public class ThreadPriority extends Thread { public void run() { System.out.println(Thread.currentThread().getPriority()); } public static void main(String[] args) throws InterruptedException { ThreadPriority t1 = new ThreadPriority(); ThreadPriority t2 = new ThreadPriority(); t1.start(); t2.start(); } }
Output :
5 5
default priority of the thread is 5.
Each thread has normal priority at the time of creation. We can change or modify the thread priority in the following example 2.
Example #2 : Setting Priority
package com.c4learn.thread; public class ThreadPriority extends Thread { public void run() { String tName = Thread.currentThread().getName(); Integer tPrio = Thread.currentThread().getPriority(); System.out.println(tName + " has priority " + tPrio); } public static void main(String[] args) throws InterruptedException { ThreadPriority t0 = new ThreadPriority(); ThreadPriority t1 = new ThreadPriority(); ThreadPriority t2 = new ThreadPriority(); t1.setPriority(Thread.MAX_PRIORITY); t0.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); t0.start(); t1.start(); t2.start(); } }
Output :
Thread-0 has priority 1 Thread-2 has priority 5 Thread-1 has priority 10
Explanation of Thread Priority :
- We can modify the thread priority using the setPriority() method.
- Thread can have integer priority between 1 to 10
- Java Thread class defines following constants -
- At a time many thread can be ready for execution but the thread with highest priority is selected for execution
- Thread have default priority equal to 5.
Thread : Priority and Constant
Thread Priority | Constant |
---|---|
MIN_PRIORITY | 1 |
MAX_PRIORITY | 10 |
NORM_PRIORITY | 5 |