Thread Priorities in Java

 Thread Priorities in Java

  • Every Thread in java have some priority.
  • It may be default priority generated by JVM or customized priority provided by programmers.
  • The valid range of a thread priorities is 1 to 10 where 1 is minimum and 10 is maximum.
  •  Thread class defined the following constants to represent some standard priorities.
    • Thread.MIN_PRIORITY    - 1
    • Thread.NORM_PRIORITY    -5
    • Thread.MAX_PRIORITY    - 1
  • Thread scheduler will use priority while allocating processor. 
  • The thread which is have highest priority will get the chance first.
  • If 2 thread have same priority then we cannot expect exact execution order. It depends on Thread scheduler 

 

Methods for Getting and Setting priorities.

 
Thread priority in java

Default Priority

  • The default priority is only for the main thread is 5.
  • But for all remaining thread default priority will be inherited from parent to child. i.e. What ever parent have, same priority will be there for child.
Thread priority in java example


Ex.

Thread priority in java example

 

If we are commenting Line 1 ( red line in main method ) in above program, then both main and child thread have the same priority 5 and hence we cannot know execution order and exact output.
 
If we are not commenting line 1 then main thread has a priority 5 and child thread has priority 10. Hence child thread will get the chance first followed by main thread. In this case output is child thread first and then main thread.

Note:

Some platform would not provide proper support for thread priority.

RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

Post a Comment (0)
Previous Post Next Post