< Prev
Next >

Threads Priorities

In java, each and every thread has a priority which is defined by a number between, 1 to 10, with 1 being the lowest priority and 10 being the highest priority. A default priority for a thread is 5 but you can even set the priority for a thread. Ideally, a thread having a maximum priority(10) should get the maximum CPU time but it's not always the case. Here's why -:

Some JVMs use time slicing scheduling of threads, where each thread gets a particular amount of time to run on CPU before it is replaced by some other thread, whereas some JVMs use pre-emptive or priority based scheduling, in which a thread with the maximum priority gets the maximum amount of time to run on CPU.

Hence, you should never base an important outcome of your program on thread priorities because setting the thread with maximum priority is not a guarantee of maximum CPU time.

How to set priority of a Thread.

To set a thread's priority, we can use setPriority() method of Thread class, which looks like this -:

Method Description
final void setPriority(int priority) Sets the priority of a Thread.

where setPriority() method can be passed an int value between number 1 to 10, or alternatively, we can even pass one of the three static final variables of Thread class -:

By default, each thread gets a default priority of 5, i.e. Thread.NORM_PRIORITY

How to get priority of a Thread.

To get a thread's priority, we can use getPriority() method of Thread class, which has a form -:

Method Description
final int getPriority() Returns the priority of a Thread.

Checking and setting the priority of Thread

Create a class that implements Runnable interface and implementing its run() method.
class ThreadRun2 implements Runnable

public void run()	//Entry Point of the new thread.
Thread t=Thread.currentThread();

//Getting the default priority of NewThread.
System.out.println("Default priority of "+ t.getName() + " : " +  t.getPriority());

//Setting the priority of NewThread to 10.

//Getting the name and priority of this thread
System.out.println("Priority of " + t.getName() + " : " + t.getPriority());  

public static void main(String... ar)
ThreadRun2 newTh = new ThreadRun2();
Thread th1= new Thread(newTh, "NewThread");//Calling Thread's constructor & passing the object
					   //of class that has implemented  Runnable interface
					   //& the name of new thread.

th1.start(); //starting the new thread, calls run() method automatically


Output is -:

Default priority of NewThread : 5
Priority of NewThread : 10

Program Analysis

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< Creating a Thread
join() in Thread>

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page


Please check our latest addition