Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

February 12, 2016 Categories: Multithreading. No Comments on Thread Priorities

In this article we will learn how to work with thread priorities when there are several threads competing for CPU time. Example code is also provided.

 

In a uni-processor system, when several threads are competing for the CPU, you might want a certain thread to get more CPU time (burst time) over the remaining threads. We can use thread priorities in such situation.

 

The thread class provides three final static variables (constants) namely: MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY whose values are 1, 5 and 10 respectively. Priority values can be in the range 1 to 10. 1 denotes minimum priority and 10 denotes maximum priority.

 

A higher priority thread always gets more CPU time over the lesser priority thread. When a lesser priority thread is currently running on a CPU and a higher priority thread resumes (after wait or sleep or unblocked from I/O), it will preempt the lesser priority thread.

 

By default all the newly created threads will have a priority of 5. For assigning a new priority to the thread, we can use setPriority() method of Thread class whose syntax is as follows:

final void setPriority(int priority_level)

 

For retrieving the priority of the thread we can use getPriority() method of Thread class whose syntax is as follows:

final int getPriority()

 

Below program demonstrates the use of setPriority() and getPriority() methods:

 

Output of the above program is:

Child thread: Thread[First Thread,5,main]
First Thread: 1
Child thread: Thread[Second Thread,5,main]
Priority of first thread is: 10
Priority of second thread is: 1
Main thread is waiting…
Second Thread: 1
First Thread: 2
First Thread: 3
First Thread: 4
First Thread: 5
First Thread: 6
Second Thread: 2
First Thread: 7
First Thread: 8
First Thread: 9
First Thread: 10
Second Thread: 3
First Thread is terminated
Second Thread: 4
Second Thread: 5
Second Thread: 6
Second Thread: 7
Second Thread: 8
Second Thread: 9
Second Thread: 10
Second Thread is terminated
Main thread terminated

Although the sleeping time of first thread is less than the second thread, in general, thread with higher priority gets more CPU time.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me