androidengineers.Book a session
โ† All interview questions
ThreadIntermediate3 min

What is Thread Priority and how to set it?

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

ConstantValueUse Case
Thread.MIN_PRIORITY1Background, non-urgent
Thread.NORM_PRIORITY5Default
Thread.MAX_PRIORITY10Critical, 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

ConstantValueUse Case
THREAD_PRIORITY_URGENT_AUDIO-19Audio playback
THREAD_PRIORITY_AUDIO-16Audio processing
THREAD_PRIORITY_URGENT_DISPLAY-8Display updates
THREAD_PRIORITY_DISPLAY-4UI work
THREAD_PRIORITY_DEFAULT0Normal
THREAD_PRIORITY_BACKGROUND10Background work
THREAD_PRIORITY_LOWEST19Least 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

  1. Priority is just a hint - OS decides actual scheduling
  2. Don't rely on priority for correctness - Use synchronization
  3. Android priorities differ from Java - Use Process.setThreadPriority() for Android
  4. UI thread has higher priority - Background work won't starve UI
  5. 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

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising