Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system chooses the new higher priority thread for execution. On the other hand, if two threads of the same priority are waiting to be executed by the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them to run according to their round of time-slice.
Thread Scheduler
In the implementation of threading scheduler usually applies one of the two following strategies:
Preemptive scheduling ? If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.
Time-Sliced (Round-Robin) Scheduling ? A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.
Example of priority of a Thread:
class ThreadPriorityDemo extends Thread{ public void run(){ System.out.println("Running thread is "+Thread.currentThread().getName()); System.out.println("Running thread priority is "+Thread.currentThread().getPriority()); } public static void main(String args[]){ ThreadPriorityDemo t1 = new ThreadPriorityDemo(); ThreadPriorityDemo t2 = new ThreadPriorityDemo(); ThreadPriorityDemo t3 = new ThreadPriorityDemo(); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t3.setPriority(Thread.NORM_PRIORITY); t1.setName("Dinesh on Java"); t2.setName("DAV JavaServices"); t3.setName("dineshonjava.com"); t1.start(); t2.start(); t3.start(); } }
Output:
In the above output of program we are observing that the output of same program is vary, its means that the outputs are depends on the OS. JVM can not guaranteed about the scheduling of threads.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…