Credits

Tuesday, August 10, 2010

Java's Thread Priorities

 A single - processor CPU can get lost as to identify which process or thread must be done first and next. Time splicing however is commonly known in recent computer systems. According to priority or time slice, a process can be selected and run.

In Java, a priority may range from 1 to 10 where 1 is the least and 10 as the highest. You can use variables like Thread.NORM_PRIORITY, Thread.MIN_PRIORITY, and Thread.MAX_PRIORITY to indicate 5, 1 and 10 priorities respectively.

See the program below for this illustration.
[+/-] show/hide




class PriThread extends Thread {

PriThread(String name, int pri) {
super(name);
setPriority(pri);
start();
}

public void run() {
System.out.println(getName()+"="+getPriority());
}
}

public class ThreadPriority {
public static void main(String args[]) throws Exception {
PriThread mt2 = new PriThread("Low Priority", Thread.NORM_PRIORITY - 1);
PriThread mt1 = new PriThread("High Priority", Thread.NORM_PRIORITY + 1);
mt1.join();
mt2.join();

}
}

AddThis