Thread priority in Java is used by the scheduler to decide which thread should be executed first. Each thread has a priority value that hints the JVM about its importance during execution.
1 to 105Thread.MIN_PRIORITY → 1Thread.NORM_PRIORITY → 5Thread.MAX_PRIORITY → 10*Note: Higher priority threads get bigger "steps" on average, but randomness (OS Scheduling) means the Max Priority thread won't always win!
// Demonstrates thread priority in Java
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " Priority: " + Thread.currentThread().getPriority());
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
The output may show threads executing in any order. However, the printed priority values confirm that priorities are set correctly. Execution order is not strictly guaranteed.
run() to simulate work