← Back to Chapters

Thread Priority in Java

? Thread Priority in Java

? Quick Overview

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.

? Key Concepts

  • Priority range is from 1 to 10
  • Default priority is 5
  • Higher priority does not guarantee execution order
  • Scheduler behavior depends on the JVM and OS

? Syntax / Theory

  • Thread.MIN_PRIORITY → 1
  • Thread.NORM_PRIORITY → 5
  • Thread.MAX_PRIORITY → 10

? Interactive Simulation

See how priority affects "CPU Time" allocation
MIN (1)
1
NORM (5)
5
MAX (10)
10

*Note: Higher priority threads get bigger "steps" on average, but randomness (OS Scheduling) means the Max Priority thread won't always win!

? Code Example(s)

? View Code Example
// 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();
}
}

? Live Output / Explanation

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.

✅ Tips & Best Practices

  • Use priorities only as hints, not for logic control
  • Avoid relying on priority for synchronization
  • Prefer proper thread coordination techniques

? Try It Yourself

  • Change thread priorities and observe output
  • Add a loop inside run() to simulate work
  • Compare behavior across different systems