Thread Priorities and yield()
In part-5 we have seen how the order of thread execution happens and the
join() method to join the currently running thread at the end of the other thread. We have also learned that there is no guarantee in the order of threads' execution. Here in this part, we’ll have a look at the thread priorities and how we expect to gracefully threads can take their turns using the
yield(). But before understanding the
yield() method, it is really important to look at thread priorities.
In Java, thread priorities are just the numbers from 1 to 10 (1: being the lowest priority and 10: the highest). The scheduler in most JVMs is priority-based preemptive scheduling with some sort of time slicing. What does that mean? Preemptive essentially means turn-taking. The threads take CPU’s turn after some time elapses and which thread to take its turn next depends on the priority of the thread.
But the thread scheduling algorithm varies from JVM to JVM. And even JVM specification doesn't specify which scheduling algorithm to use. It all depends on how the thread scheduler is implemented in a particular JVM. We cannot even guarantee whether all the JVMs use thread priorities in the first place. They may also use Round-Robin with a time slice. There is no such rule enforced anywhere in JVM Spec. But in most of the JVMs, the thread scheduler does use the priorities in one important way: That is when a thread enters the runnable queue and it has higher priority than any of the threads in the queue or the higher priority than the currently running thread, then the lower priority running thread will be pushed back to the runnable queue and the highest priority running thread will be chosen to run.
In most cases, the running thread will be of equal or greater priority than the highest-priority thread in the queue. Once again, there is no guarantee and we should NOT rely on thread priorities to state the correctness of our program.
NOTE: Never ever rely on thread priorities to guarantee the correctness of your multithreaded application. What is also not guaranteed is which thread will get picked up from the queue when all the threads have the same priority.