Thread Priorities

Every Java thread has a thread priority that helps the operating system determine the order in which threads are scheduled. Java priorities range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Each new thread inherits the priority of the thread that created it. Informally, higher-priority threads are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute.

An operating system’s thread scheduler determines which thread runs next. One simple thread scheduler implementation keeps the highest-priority thread running at all times and, if there is more than one highest-priority thread, ensures that all such threads execute for a quantum each in round-robin fashion.

Example as follows :

class MyThread extends Thread {
	MyThread(String name) {
		super(name);
	}

	public void run() {
		System.out.println(this.getName());
	}
}

public class Example3 {
	public static void main(String[] args) {
		MyThread a = new MyThread("A");
		MyThread b = new MyThread("B");
		MyThread c = new MyThread("C");

		a.setPriority(Thread.MIN_PRIORITY); // equivalent to a.setPriority(10)
		b.setPriority(Thread.NORM_PRIORITY); // equivalent to a.setPriority(5)
		c.setPriority(Thread.MAX_PRIORITY); // equivalent to a.setPriority(1)

		a.start();
		b.start();
		c.start();
	}
}