Thread Priority in Java

Thread priority in Java is a way to indicate importance or preference of one thread’s execution over another. Threads with higher priority values are scheduled to run before then those with lower priority values. Higher-priority threads are more likely to be given CPU time before then lower-priority threads.

However, it’s important to note that the actual behavior of thread priorities can vary across operating systems and even within the same operating system, depending on the version and other factors.

The Thread class defines three constants for thread priorities:

  • MIN_PRIORITY: The minimum priority. The value of this constant is 1.
  • NORM_PRIORITY: The normal priority. The value of this constant is 5.
  • MAX_PRIORITY: The maximum priority. The value of this constant is 10

By default, newly created threads are given the same priority as the thread that created them. However, we can change a thread’s priority using the setPriority method, which takes an integer value between 1 and 10 as an argument, with 1 being the lowest priority and 10 being the highest.

Following is an example of how to use the setPriority method:

public class ThreadPriorityExample {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 1: " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.setPriority(Thread.MIN_PRIORITY);
        
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 2: " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.setPriority(Thread.MAX_PRIORITY);
        
        t1.start();
        t2.start();
    }
}

In this example, we created two threads with different priorities using the Thread class’s MIN_PRIORITY and MAX_PRIORITY constants. The threads simply print out their names and a counter and then sleep for half a second.

If we run this code, we might see output similar to the following:

Thread 2: 0
Thread 1: 0
Thread 2: 1
Thread 1: 1
Thread 2: 2
Thread 1: 2
Thread 2: 3
Thread 1: 3
Thread 2: 4
Thread 1: 4

As we can see, the higher priority thread (Thread 2) is more likely to be given CPU time and is able to print more messages. However, the exact behavior will depend on the operating system and other factors.

Hence, you may see different output in your system.

Instead of relying on thread priorities, it’s often better to use other concurrency constructs such as java.util.concurrent package’s Executor framework or the synchronized keyword to synchronize access to shared resources.

It’s also worth noting that some Java virtual machines (JVMs) may not support thread priorities, in which case the setPriority method will have no effect. In these cases, all threads will have the same priority and the operating system’s scheduling policies will be used to determine which thread should run next. While thread priorities can be useful in some cases, it’s important to use them with caution and consider other concurrency constructs as well.

In the example above, we used the MIN_PRIORITY and MAX_PRIORITY constants to set the thread priorities. However, we can also use any integer value between 1 and 10 as the priority. For example, the following code would set the priority of a thread to 5:

Thread t = new Thread(() -> {
    // code goes here
});
t.setPriority(5);

Keep in mind that using values outside of the range of 1 to 10 may cause an IllegalArgumentException to be thrown.

It’s also worth noting that the priority of a thread does not guarantee that it will always be given CPU time over other threads. It simply provides a hint to the operating system about which threads should be given priority. The actual behavior can vary and is ultimately up to the operating system’s scheduling policies.

FAQs

What is the default thread priority in Java?

The default thread priority in Java is typically 5, which is considered a moderate priority. You can check the default priority using Thread.NORM_PRIORITY.

How to set thread priority in Java?

You can set the priority of a thread using the setPriority() method. For example, the following code sets the priority of the current thread to the maximum priority:
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

When should I not use thread priority?

You should generally avoid using thread priority unless you have a specific need for it. This is because thread priority can lead to unpredictable behavior and can make your code more difficult to debug.