Thread Priority in Java
Every Java thread has a priority, a number from 1 (lowest) to 10 (highest). The priority is a hint to the thread scheduler that some threads are more important than others. By default, a thread has the same priority as the thread that created it, usually 5. However, the operating system is free to ignore priorities, so they must not be used to make a program correct. In this lesson, you will learn how to read and set priorities, and why they matter so little in practice.
Priority Constants
| Constant | Value |
|---|---|
Thread.MIN_PRIORITY | 1 |
Thread.NORM_PRIORITY | 5 (the default) |
Thread.MAX_PRIORITY | 10 |
Methods
| Method | Description |
|---|---|
setPriority(int p) | It is used to set the priority (1 to 10); other values throw IllegalArgumentException. |
getPriority() | It returns the priority. |
Example: Setting Priorities
Let's see an example that sets and reads priorities.
public class Priorities {
public static void main(String[] args) throws InterruptedException {
System.out.println("main priority: "
+ Thread.currentThread().getPriority());
Thread low = new Thread(() -> { }, "low");
Thread high = new Thread(() -> { }, "high");
low.setPriority(Thread.MIN_PRIORITY);
high.setPriority(Thread.MAX_PRIORITY);
System.out.println(low.getName() + ": " + low.getPriority());
System.out.println(high.getName() + ": " + high.getPriority());
Thread child = new Thread(() -> System.out.println(
"child inherits: " + Thread.currentThread().getPriority()));
child.start();
child.join();
try {
low.setPriority(11);
} catch (IllegalArgumentException e) {
System.out.println("Priority 11 rejected");
}
}
}main priority: 5
low: 1
high: 10
child inherits: 5
Priority 11 rejectedExplanation: The main thread has the normal priority, 5. Priorities can be set from 1 to 10, and a new thread inherits its creator's priority. A value outside the range is rejected.
Why Priorities Are Unreliable
- On many systems, Java priorities are mapped onto a few operating-system levels, or ignored completely.
- On a computer with free cores, every runnable thread runs anyway, whatever its priority.
- Virtual threads (Java 21) always have priority 5;
setPriorityhas no effect on them.
Common Mistakes
Using priorities to control order. Use join, locks or queues.
Setting all threads to MAX_PRIORITY. It changes nothing and can starve system threads on some platforms.
Practice
- Easy: Print the priority of the main thread and of a new thread created from it.
- Harder: Start one
MIN_PRIORITYand oneMAX_PRIORITYthread that each count to 100 million, and compare which finishes first over several runs. Explain your results.
Key Takeaways
Was this tutorial helpful?