Credits

Thursday, January 20, 2011

Java's Thread Prioritization

Threads in Java may run concurrently, synchronously or asynchronously and to make sure that thread are not deprived, we can set priority or rankings on our threads. We execute threads with higher priority and let CPU allot the needed resources for execution.


Threads can be ranked from 1 to 10; the higher the priority, the faster they get run. Threads with similar priority take turns to be executed.


The program below shows an example on thread's priority.
[+/-] 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