Questions
ThreadIntermediate3 min
What is Thread Priority and how to set it?
Thread Priority
Answer
What is Thread Priority?
Thread priority is a hint to the OS scheduler about how important a thread is relative to others. Higher priority threads are more likely to get CPU time.
Priority Range
| Constant | Value | Use Case |
|---|---|---|
| Thread.MIN_PRIORITY | 1 | Background, non-urgent |
| Thread.NORM_PRIORITY | 5 | Default |
| Thread.MAX_PRIORITY | 10 | Critical, time-sensitive |
Setting Thread Priority
Java/Kotlin Thread
val thread = Thread { // Low priority background work } thread.priority = Thread.MIN_PRIORITY thread.start() // Or inside the thread Thread { Thread.currentThread().priority = Thread.MAX_PRIORITY // High priority work }.start()
Android-Specific: Process.setThreadPriority()
Android provides finer control with Process.setThreadPriority():
Thread { // Set Android thread priority (different scale!) Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) // -20 (highest) to 19 (lowest), 0 is default }.start()
Android Priority Constants
| Constant | Value | Use Case |
|---|---|---|
| THREAD_PRIORITY_URGENT_AUDIO | -19 | Audio playback |
| THREAD_PRIORITY_AUDIO | -16 | Audio processing |
| THREAD_PRIORITY_URGENT_DISPLAY | -8 | Display updates |
| THREAD_PRIORITY_DISPLAY | -4 | UI work |
| THREAD_PRIORITY_DEFAULT | 0 | Normal |
| THREAD_PRIORITY_BACKGROUND | 10 | Background work |
| THREAD_PRIORITY_LOWEST | 19 | Least important |
Practical Example
class BackgroundTask : Thread() { override fun run() { // Mark as background priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) // Now this thread won't compete with UI thread performHeavyWork() } }
Important Notes
- Priority is just a hint - OS decides actual scheduling
- Don't rely on priority for correctness - Use synchronization
- Android priorities differ from Java - Use Process.setThreadPriority() for Android
- UI thread has higher priority - Background work won't starve UI
- Coroutines handle this automatically - Dispatchers.IO uses appropriate priorities
Best Practice
In modern Android, let the framework handle priorities:
- Use Dispatchers.Default for CPU work
- Use Dispatchers.IO for I/O work
- Use WorkManager for deferrable background work
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚