Scheduling with Thread Priorities

Let’s delve into the programming that affects thread scheduling; we’ll start by examining how to manipulate the priority level of Java threads. This is the most useful mechanism available to a Java programmer that affects scheduling behavior of threads; often, a few simple adjustments of thread priorities is all that’s required to make a program behave as desired.

Priority-Related Calls in the Java API

In the Java Thread class, there are three static final variables that define the allowable range of thread priorities:

Thread.MIN_PRIORITY

The minimum priority a thread can have

Thread.MAX_PRIORITY

The maximum priority a thread can have

Thread.NORM_PRIORITY

The default priority for threads in the Java interpreter

Every thread has a priority value that lies somewhere in the range between MIN_PRIORITY (which is 1) and MAX_PRIORITY (which is 10). However, not all threads can have a value anywhere within this range: each thread belongs to a thread group, and the thread group has a maximum priority (lower than or equal to MAX_PRIORITY) that its individual threads cannot exceed. We’ll discuss this further in Chapter 10, but for now, you should be aware that the maximum thread priority for a thread within an applet is typically NORM_PRIORITY + 1. In addition, the virtual machine is allowed to create internal threads at a priority of 0, so that there are in effect 11 different priority levels for threads within the virtual machine.

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.