Thread Priorities

In Java, thread priorities are used to indicate the importance or urgency of a thread relative to other threads in the same process. Thread priority is an integer value ranging from 1 to 10, where 1 is the lowest priority and 10 is the highest priority. Threads with higher priorities are more likely to be scheduled to run by the thread scheduler, but it’s important to note that thread priorities are just a hint to the scheduler and might behave differently on different platforms.

The Thread class provides several constants that represent the priority levels for threads. These constants are predefined and can be used when setting the priority of a thread using the setPriority() method. Here are the thread priority constants available in Java:

  1. Thread.MIN_PRIORITY: This constant represents the minimum thread priority. It has a value of
  2. Thread.NORM_PRIORITY: This constant represents the default or normal thread priority. It has a value of 5. It is typically used when the priority does not need to be explicitly set.
  3. Thread.MAX_PRIORITY: This constant represents the maximum thread priority. It has a value of 10.

To set the priority of a thread, you can use the setPriority() method provided by the Thread class.  This setPriority() method sets the priority of the thread to the specified integer value.

public final void setPriority(int newPriority)Code language: PHP (php)

The newPriority parameter should be an integer between 1 (lowest priority) and 10 (highest priority).

To get the priority of a thread, you can use the getPriority() method provided by the Thread class. This  method returns the priority of the thread as an integer value ranging from 1 to 10.

public int getPriority()Code language: PHP (php)

Here’s an example that demonstrates Thread Prorities

//ThreadPriority.java
class MyRunnable implements Runnable {
    public void run() {
        for (int i = 1; i <= 9; i++) {
                
        System.out.println(Thread.currentThread().getName() + "  
                  at step= " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "Rajesh");
        Thread t2 = new Thread(new MyRunnable(), "Mahesh");

        // Setting priorities
        t1.setPriority(Thread.MIN_PRIORITY); // 1
        t2.setPriority(Thread.MAX_PRIORITY); // 10
        System.out.println("Rajesh Priority="+t1.getPriority());
		System.out.println("Mahesh Priority="+t2.getPriority());
        // Starting the threads
        t1.start();
        t2.start();
    }
}

Output:

D:\>javac ThreadPriorityDemo.java
D:\>java ThreadPriorityDemo
Rajesh Priority=1
Mahesh Priority=10
Rajesh at step= 1
Mahesh at step= 1
Mahesh at step= 2
Rajesh at step= 2
Mahesh at step= 3
Rajesh at step= 3
Mahesh at step= 4
Rajesh at step= 4
Mahesh at step= 5
Rajesh at step= 5
Mahesh at step= 6
Rajesh at step= 6
Mahesh at step= 7
Rajesh at step= 7
Mahesh at step= 8
Rajesh at step= 8
Mahesh at step= 9
Rajesh at step= 9

In the above example, we create two threads with different priorities and start them. Thread-1 has the lowest priority (1), while Thread-2 has the highest priority (10).

Thread Priorities  from Car Race Scenario

Let’s consider a car racing scenario where multiple cars are competing. We can use threads to simulate the movement of each car and assign thread priorities to represent their positions in the race.

Here’s an example that demonstrates the usage of Thread class and creation of threads:

//CarRaceDemo.java
class Car extends Thread {
    private final String name;
    private int distance = 0;

    public Car(String name) {
        this.name = name;
    }

    public void run() {
        while (distance < 90) { // Race track length is 100 units
            distance += 9; // Car moves forward by 10 units
            System.out.println(name + " has covered " + distance + " units.");

            try {
                Thread.sleep(1000); // Delay to simulate car movement
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(name + " has finished the race!");
    }
}

public class CarRaceDemo {
    public static void main(String[] args) {
        Car car1 = new Car("Maruthi");
        Car car2 = new Car("Hyundai");
        Car car3 = new Car("Kia EV5");

        // Assigning priorities
        car1.setPriority(Thread.MAX_PRIORITY); // Maruthi has highest priority
        car2.setPriority(Thread.NORM_PRIORITY); // Hyundai has normal priority
        car3.setPriority(Thread.MIN_PRIORITY); // Kia EV5 has lowest priority

        // Starting the race
        car1.start();
        car2.start();
        car3.start();
		try {
             car1.join(); // Delay to simulate car movement
			 car2.join();
			 car3.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

Output:

D:\>javac CarRaceDemo.java
D:\>java CarRaceDemo
Maruthi has covered 9 units.
Kia EV5 has covered 9 units.
Hyundai has covered 9 units.
Maruthi has covered 18 units.
Hyundai has covered 18 units.
Kia EV5 has covered 18 units.
Maruthi has covered 27 units.
Kia EV5 has covered 27 units.
Hyundai has covered 27 units.
Hyundai has covered 36 units.
Kia EV5 has covered 36 units.
Maruthi has covered 36 units.
Hyundai has covered 45 units.
Kia EV5 has covered 45 units.
Maruthi has covered 45 units.
Maruthi has covered 54 units.
Kia EV5 has covered 54 units.
Hyundai has covered 54 units.
Hyundai has covered 63 units.
Kia EV5 has covered 63 units.
Maruthi has covered 63 units.
Maruthi has covered 72 units.
Kia EV5 has covered 72 units.
Hyundai has covered 72 units.
Maruthi has covered 81 units.
Kia EV5 has covered 81 units.
Hyundai has covered 81 units.
Maruthi has covered 90 units.
Kia EV5 has covered 90 units.
Hyundai has covered 90 units.
Maruthi has finished the race!
Hyundai has finished the race!
Kia EV5 has finished the race!
*/

By assigning different thread priorities to the cars, we can influence the scheduling order and simulate a race where the car with the highest priority is more likely to make progress and finish earlier than others. However, please note that thread priorities are not a precise mechanism for determining the order of execution, and the actual behaviour may vary depending on the JVM and platform.

Note
  • Keep in mind that thread priorities are just a hint, and the actual behavior might vary across different Java Virtual Machine (JVM) implementations and operating systems.
  • In general, it’s not recommended to rely heavily on thread priorities for critical application logic, as it can lead to platform-dependent behavior and potential thread starvation.
  • Instead, it’s often better to design your application in a way that doesn’t heavily rely on thread priorities for correctness.

References

Thread class from java docs
Scroll to Top