🧠 What is Thread Priority?
Thread priority is a number that tells the JVM and operating system how “important” a thread is relative to other threads.
In theory:
🔼 Higher-priority threads are given more CPU time than lower-priority ones.
📦 How You Set It
In Java, every thread has a priority between 1
(MIN) and 10
(MAX), with 5
as the default (Thread.NORM_PRIORITY
):
Thread t = new Thread(() -> {
// thread logic
});
t.setPriority(Thread.MAX_PRIORITY); // 10
📌 Constants for Clarity
Constant | Value |
---|---|
Thread.MIN_PRIORITY | 1 |
Thread.NORM_PRIORITY | 5 |
Thread.MAX_PRIORITY | 10 |
🕹️ But… Does It Actually Work?
✔ In theory (Java Language Specification):
- Thread priorities should influence thread scheduling.
❌ In practice:
- It’s mostly up to the OS scheduler, and often ignored:
- On Windows, it may work to some extent.
- On Linux, the JVM usually ignores it unless you’re using real-time scheduling policies.
- On modern CPUs, core load balancing and OS-level fairness make priority unreliable.
So: don’t rely on thread priorities for correctness — use proper concurrency control (locks, semaphores, etc.).
🧪 Example (Just for Experimenting):
public class ThreadPriorityDemo {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName());
}
};
Thread low = new Thread(task, "Low Priority");
Thread high = new Thread(task, "High Priority");
low.setPriority(Thread.MIN_PRIORITY); // 1
high.setPriority(Thread.MAX_PRIORITY); // 10
low.start();
high.start();
}
}
👀 You might see more lines from High Priority
, but don’t be surprised if the OS doesn’t care.
✅ When to Use It
- For non-critical hints to the JVM/OS scheduler.
- Never use it for essential logic (like locking or sequencing threads).
🧠 Summary
Feature | Description |
---|---|
What it is | Hint to the scheduler about thread importance |
Range | 1 (low) to 10 (high) |
Reliable? | ❌ Not really — depends on OS/JVM |
Better tools | Executors , semaphores, Locks , etc. |