In a single processor machine, only one thread can actually run at a time. Any thread in the ready state can be chosen by the scheduler. The order in which the runnable (ready) threads execute, can not be predicted. In other words, the behavior of scheduler cannot be controlled or planned in advance. But, sometimes, we can influence the scheduler by specifying the priority of the thread.
The priority of a thread conveys the importance of a thread to the scheduler. The thread having higher priority run more frequently as compared to low priority threads. However, it does not mean that the threads with low priority do not run. Low priority threads just tend to run less often. By default, all the threads have same priority i.e. NORM_PRIORITY.
NORM_PRIORITY is a public, final and static int type variable of Thread class, with preassigned value.
The Priority of a thread can be between 1 and 10. 1 represent lowestpriority and 10 represent highest priority. The Thread class consist of two more public, final and static and int type variables i.e. MAX_PRIORITY with preassigned value 10 and MIN_ PRIORITY having preassigned value:1.
You can also get the priority of a thread by calling getPriority() method of Thread class.
Implementation:
The following program demonstrates the use of setPriotity() and getPriority() methods to influence the scheduler.
// PriorityDemo.java class Clicker extends Thread { int count=0; boolean flag=true; public void run() { while(flag) { count++; } System.out.println(“thread:”+getName()+” processed “+count+”times”); } } public class PriorityDemo { public static void main(String[] args) { Clicker thrd1=new Clicker(); thrd1.setName(“Max priority”); thrd1.setPriority(Thread.MAX_PRIORITY); Clicker thrd2=new Clicker(); thrd2.setName(“Min priority”); thrd2.setPriority(Thread.MIN_PRIORITY); thrd1.start(); thrd2.start(); try{ Thread.sleep(200); } catch(Exception ex) {ex.printStackTrace(); } thrd1.flag=false; thrd2.flag=false; } }
Output thread:Max priority processed 89042290 times thread:Min priority processed 86321660 times