By WebNest Studio Engineering Team
Java - Core Tutorial
Thread Priority and sleep()
Java gives every thread an integer priority that hints to the thread scheduler how much CPU preference it should receive relative to other threads, and it gives every thread the ability to pause its own execution for a fixed period using Thread.sleep(). Both mechanisms influence when a thread runs, but neither one guarantees exact timing or exact ordering, because the underlying OS scheduler ultimately makes the real decisions.
Why it matters
Thread.sleep() is the simplest way to pause, and it appears in retries, polling loops and tests. It forces you to deal with InterruptedException, which most beginners swallow incorrectly. Priorities are the opposite case: they look powerful but are only a hint, and relying on them for correctness is a mistake.
Thread Priority
Every thread has a priority in the range 1 to 10, controlled by setPriority(int) and read with getPriority(). Three named constants exist on Thread: MIN_PRIORITY (1), NORM_PRIORITY (5, the default for new threads unless inherited from the parent), and MAX_PRIORITY (10). A higher priority is only a hint to the scheduler that this thread should be favored for CPU time — it does not guarantee that a higher-priority thread runs first, runs more often, or finishes earlier, and behavior can vary noticeably across operating systems and JVM implementations. Priority should never be used as a substitute for proper synchronization or correctness logic.
Thread.MIN_PRIORITY= 1Thread.NORM_PRIORITY= 5 (default)Thread.MAX_PRIORITY= 10
Thread.sleep()
Thread.sleep(long millis) pauses the currently executing thread for at least the given number of milliseconds (an overload also accepts nanoseconds), moving it into the TIMED_WAITING state. Because sleeping is interruptible, sleep() declares a checked exception, InterruptedException, which must be caught or declared. Importantly, sleeping does not release any intrinsic locks the thread currently holds — a thread that sleeps while inside a synchronized block continues to hold that lock the entire time, which can block other threads unexpectedly if not designed carefully.
sleep() Is Not a Precision Timer
sleep() guarantees the thread will sleep for at least the requested duration, not exactly that duration — OS scheduling granularity, system load, and JVM garbage collection pauses can all add extra delay. It should be used for approximate pacing (throttling, retry backoff, simple demos) rather than for time-critical operations.
Example
Setting priority and using sleep() with proper exception handling
public class PriorityAndSleepDemo {
public static void main(String[] args) throws InterruptedException {
Thread low = new Thread(() -> System.out.println("Low priority thread ran"));
low.setPriority(Thread.MIN_PRIORITY);
Thread high = new Thread(() -> System.out.println("High priority thread ran"));
high.setPriority(Thread.MAX_PRIORITY);
System.out.println("low priority: " + low.getPriority());
System.out.println("high priority: " + high.getPriority());
low.start();
high.start();
low.join();
high.join();
System.out.println("Main thread sleeping for 300ms...");
Thread.sleep(300);
System.out.println("Main thread resumed after sleep");
}
}
low priority: 1
high priority: 10
Main thread sleeping for 300ms...
Main thread resumed after sleep
(Note: "Low priority thread ran" and "High priority thread ran" can print in either order —
priority is only a scheduling hint, not a guaranteed execution order.)
Common Mistakes
- Relying on thread priority to guarantee a specific execution order — it is only a scheduling hint and behaves differently across JVMs and operating systems.
- Forgetting that Thread.sleep() throws a checked InterruptedException, and either failing to handle it or silently swallowing it without restoring the interrupt status.
- Assuming sleep() releases locks held by the thread — a sleeping thread inside a synchronized block still holds that lock, which can cause unexpected contention.
- Using sleep() for precise timing in production code instead of a proper scheduling API, when exact timing actually matters.
Exercise
Print a countdown from 3 to 1, pausing 200 milliseconds between numbers, and then print Go. Handle the checked exception that sleep can throw.
Expected output: 3, 2, 1, Go
public class Countdown {
public static void main(String[] args) {
for (int i = 3; i >= 1; i--) {
System.out.println(i);
// TODO: pause for 200 milliseconds, handling InterruptedException
}
System.out.println("Go");
}
}
Show hints
Thread.sleep(200)throws the checkedInterruptedException, so it needs a try-catch here.- When you catch it, restore the flag with
Thread.currentThread().interrupt()rather than ignoring it.
Show solution
public class Countdown {
public static void main(String[] args) {
for (int i = 3; i >= 1; i--) {
System.out.println(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
System.out.println("Go");
}
}
Quick quiz
1. What is the default priority of a new thread created from the main thread?
- A. 1
- B. 10
- C. 5
- D. 0
Show answer
C. A thread inherits the priority of the thread that created it. The main thread has NORM_PRIORITY, which is 5.
2. What is the valid range for a thread's priority?
- A. 0 to 100
- B. -1 to 1
- C. 1 to 5
- D. 1 to 10
Show answer
D. MIN_PRIORITY is 1 and MAX_PRIORITY is 10. A value outside that range throws IllegalArgumentException.
3. A thread holding a lock calls Thread.sleep(1000). What happens to the lock?
- A. It is kept; sleep does not release locks
- B. It is released for the duration
- C. It is passed to the next thread
- D. It is destroyed
Show answer
A. sleep pauses the thread but keeps every lock it holds, so other threads waiting for that lock stay blocked.
Interview questions
Does a higher priority guarantee that a thread runs first?
Show answer
No. Priority is a hint to the scheduler, and how it is honoured depends on the operating system. A high-priority thread is likely to get more processor time, but there is no guarantee of order. Code that needs a particular order must use coordination tools such as join(), locks or latches, never priorities.
What is the difference between sleep() and wait()?
Show answer
Thread.sleep() is a static method that pauses the current thread for a fixed time and keeps any locks it holds. wait() is called on an object from inside a synchronized block; it releases that object's lock and pauses until another thread calls notify() or notifyAll() on the same object, or a timeout expires.
Key Points to Remember
- Thread priority ranges from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5 (NORM_PRIORITY) as the default; it is a hint, not a guarantee.
- Thread.sleep(ms) pauses the current thread and throws checked InterruptedException.
- A sleeping thread does not release any intrinsic locks it holds.
- sleep() guarantees a minimum delay, not an exact one.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering