Thread Priority

In a single processor machine, only one thread can actually run at a time. Any thread in the ready state can be chosen by the scheduler. The order in which the runnable (ready) threads execute, can not be predicted. In other words, the behavior of scheduler cannot be controlled or planned in advance. But, sometimes, we can influence the scheduler by specifying the priority of the thread.

The priority of a thread conveys the importance of a thread to the scheduler. The thread having higher priority run more frequently as compared to low priority threads. However, it does not mean that the threads with low priority do not run. Low priority threads just tend to run less often. By default, all the threads have same priority i.e. NORM_PRIORITY.

NORM_PRIORITY is a public, final and static int type variable of Thread class, with preassigned value.
The Priority of a thread can be between 1 and 10. 1 represent lowest­priority and 10 represent highest priority. The Thread class consist of two more public, final and static and int type variables i.e. MAX_PRIORITY with preassigned value 10 and MIN_ PRIORITY having preassigned value:1.
You can also get the priority of a thread by calling getPriority() method of Thread class.
The following program demonstrates the use of setPriotity() and getPriority() methods to influence the scheduler.

class Clicker extends Thread
     {	int count=0;
	boolean flag=true;
	public void run()
  	  {  while(flag)
	        {	count++;   }
System.out.println(“thread:”+getName()+” processed “+count+”times”);
public class PriorityDemo 
   {	public static void main(String[] args) 
		{	Clicker thrd1=new Clicker();
			thrd1.setName(“Max priority”);
			Clicker thrd2=new Clicker();
			thrd2.setName(“Min priority”);
			try{ Thread.sleep(200); }
			catch(Exception ex)
			{ex.printStackTrace();	}
	thread:Max priority processed 89042290 times 
	thread:Min priority processed 86321660 times

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on
#Email : #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "". M:9872246056
Card image cap