Interview Q&A · Java · 7 questions in this topic

Thread Priorities, yield() and Control Methods — Java Interview Q&A

All Java topics

How thread priorities and yield work, and why they are only hints to the scheduler. Part of Threads & Concurrency · 294 questions in the Java bank.

What are thread priorities?

Answer

Thread priorities are integer hints from 1 to 10 that suggest how urgently a thread should be scheduled. A new thread inherits the priority of the thread that created it, and the main thread normally runs at NORM_PRIORITY, which is 5. The scheduler may favour higher priority threads, but it is not required to do so. Correct code therefore treats priorities as tuning hints, never as guarantees of order.

What priority constants exist?

Answer

The Thread class defines three named constants for the allowed range. MIN_PRIORITY is 1 for the lowest priority, NORM_PRIORITY is 5 for the default priority, and MAX_PRIORITY is 10 for the highest priority. Custom priorities must fall between MIN_PRIORITY and MAX_PRIORITY inclusive. Using the named constants is clearer than hard-coding numbers.

Key points

  1. 1MIN_PRIORITY with value 1 for background work.
  2. 2NORM_PRIORITY with value 5, the default for new threads.
  3. 3MAX_PRIORITY with value 10 for urgent work.

How is a thread priority changed?

Answer

You read it with getPriority and change it with setPriority before or after the thread starts. The argument must be between MIN_PRIORITY and MAX_PRIORITY, otherwise setPriority throws IllegalArgumentException. Changing the priority only nudges the scheduler and does not guarantee execution order. Portable programs therefore use priorities only for coarse tuning, not for correctness.

Example

Example.javajava
Thread t = new Thread(() -> System.out.println("work"));
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("priority: " + t.getPriority());

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits