What are thread priorities in java programming

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/thread-priorities-java-programming/

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.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/thread-priorities-java-programming/

Add a Comment

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

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger