Priority of a Thread
Priority of a Thread
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread gets the ready-to-run state according to theirpriorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-runstate.
3 constants defined in Thread class:
- public static int MIN_PRIORITY
- public static int NORM_PRIORITY
- public static int MAX_PRIORITY
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 runtimesystem 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 whichthe 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(); } }
post a comment