Threads in Java — Part 5 (Thread Priority)
In Java, each thread have a priority up to 10. The highest priority is 10 while the lowest priority is 1 and normal priority is consider as 5. In Java, we have ThreadPriority class with different methods such as getPriority(), setPriority() as well instances like MIN_PRIORITY, MAX_PRIORITY, NORM_PRIORITY.
Thread Scheduler in JVM is responsible for setting up priorities for each thread in the system.
- If you set priority in child thread as 1, then majority of child thread will be ended-up at the bottom of execution since it gets the lowest priority.
- Let’s check initial priority of Main thread by using getPriority().
Output:
The thread priority in main thread: 5
Therefore, JVM set initial priority for main thread as 5 because no one creates it but JVM.
Does always default priority is 5 in main and child thread?
- T his is some confused question. Let’s check whether to is it always 5 or not. Let’s see about this in detailed. Here, I’m going to check the priorities of both and child threads without assigning.
Output:
The thread priority in main thread: 5
The thread priority in child thread: 5
Here, you can see that the both threads consume as priority 5 as their default thread in this time.
- But, let’s set the priority for the main thread as 6 to see the initial default behavior of child thread.
For more clarification, we can check the initial default priority of main thread by setting as “The initial priority of main thread:” statement.
Output:
The initial priority of main thread: 5
The thread priority in main thread: 6
The thread priority in child thread: 6
Now you can see, before setting up priority for main thread it gets priority as 5 which is initially assigned by JVM. But, after we assign main thread priority as 6 the initial default thread also get the priority as 6 not 5.
That means the default priority of child thread is not always gained as 5. It inherits the priority obtained by its immediate main thread.
What will happen if we set the priority of the thread beyond 10?
If you set priority beyond 10, then you will definitely get illegal argument exception error in thread since you set priority beyond its limit.
Hope you get better understand about the thread priority and idea of thread scheduling also. In the next article we are going to discuss about the Thread join and Thread Life cycle.
Stay Safe !!!
References:
https://www.youtube.com/watch?v=K70ZU8dgU6w&list=PLD-mYtebG3X99o6vJ3uR5P6UcH3MQSWBH&index=4