The perfect place for easy learning...

Java Programming

×

Topics List


Java Thread Priority





In a java programming language, every thread has a property called priority. Most of the scheduling algorithms use the thread priority to schedule the execution sequence. In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10 is considered as the highest priority. The thread with more priority allocates the processor first.

The java programming language Thread class provides two methods setPriority(int), and getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and they are listed below.

  • MAX_PRIORITY - It has the value 10 and indicates highest priority.
  • NORM_PRIORITY - It has the value 5 and indicates normal priority.
  • MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).

setPriority( ) method

The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer range from 1 to 10 as an argument and returns nothing (void).

The regular use of the setPriority( ) method is as follows.

Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);

getPriority( ) method

The getPriority( ) method of Thread class used to access the priority of a thread. It does not takes anyargument and returns name of the thread as String.

The regular use of the getPriority( ) method is as follows.

Example
String threadName = threadObject.getPriority();

Look at the following example program.

Example
class SampleThread extends Thread{
	public void run() {
		System.out.println("Inside SampleThread");
		System.out.println("Current Thread: " + Thread.currentThread().getName());
	}
}

public class My_Thread_Test {

	public static void main(String[] args) {
		SampleThread threadObject1 = new SampleThread();
		SampleThread threadObject2 = new SampleThread();
		threadObject1.setName("first");
		threadObject2.setName("second");
		
		threadObject1.setPriority(4);
		threadObject2.setPriority(Thread.MAX_PRIORITY);
		
		threadObject1.start();
		threadObject2.start();
		
	}
}

When we run this code, it produce the following output.

thread priority in java

🔔 In java, it is not guaranteed that threads execute according to their priority because it depends on JVM specification that which scheduling it chooses.