Thread scheduling in operating systems generally follows one of two models: preemptive or cooperative (non-preemptive). Under a preemptive model, the operating system interrrupts threads and allocates CPU time based on a scheduling algorithm. This introduces unpredictability—any eligible thread may run at any moment, and time slices vary. Cooperative scheduling, in contrast, allows each thread to execute until it voluntarily yields control, typically resulting in more uniform execution times. The Java Virtual Machine relies on the underlying platform's scheduler, which is overwhelmingly preemptive on modern systems.
Priority influences a thread's statistical likelihood of acquiring CPU cycles. In Java, the Thread class defines a priority scale from 1 to 10, with 5 as the default for newly created threads. Three constants formalize these boundaries:
Thread.MIN_PRIORITY— value1Thread.NORM_PRIORITY— value5Thread.MAX_PRIORITY— value10
The Thread class exposes two methods for managing this property:
| Method | Description |
|---|---|
final int getPriority() |
Returns the trhead's current priority. |
final void setPriority(int priority) |
Updates the thread's priority to a value between 1 and 10. |
Consider the following demonstration. A Worker task prints a short sequence of values, allowing us to observe scheduling order under different priorities.
class Worker implements Runnable {
@Override
public void run() {
for (int step = 1; step <= 50; step++) {
System.out.println(Thread.currentThread().getName() + " -> " + step);
}
}
}
The test routine below creates two threads from the same task and inspects their default priorities, along with that of the main thread:
Worker job = new Worker();
Thread highWorker = new Thread(job, "Priority-High");
Thread lowWorker = new Thread(job, "Priority-Low");
System.out.println(highWorker.getPriority()); // 5
System.out.println(lowWorker.getPriority()); // 5
System.out.println(Thread.currentThread().getPriority()); // 5
All three report 5, confirming that the initial priority equals Thread.NORM_PRIORITY. You can bias the scheduler by assigning explicit levels:
highWorker.setPriority(Thread.MAX_PRIORITY); // 10
lowWorker.setPriority(Thread.MIN_PRIORITY); // 1
highWorker.start();
lowWorker.start();
Because Priority-High holds a greater scheduling weight, it generally receives more CPU time and tends to complete sooner. Yet the JVM does not guarantee any fixed execution sequence—platform-specific scheduler implementations and thread states mean a low-priority thread can still preempt a high-priority one. Application logic must not rely on priority for correctness.