Thread Priorities in java

Thread priorities in Java are used to indicate the importance or urgency of a thread in relation to other threads. Java assigns each thread a priority ranging from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with the default priority being Thread.NORM_PRIORITY (5). Thread priorities are hints to the scheduler about the importance of a thread, but they do not guarantee the order of execution.

Setting Thread Priority:

Thread priority can be set using the setPriority() method, and it can be retrieved using the getPriority() method. The methods are part of the Thread class.

Thread thread = new Thread();
thread.setPriority(Thread.NORM_PRIORITY); // Set thread priority
int priority = thread.getPriority(); // Get thread priority

Thread Priorities Constants:

  • Thread.MIN_PRIORITY: Minimum thread priority. Corresponds to priority 1.
  • Thread.NORM_PRIORITY: Default thread priority. Corresponds to priority 5.
  • Thread.MAX_PRIORITY: Maximum thread priority. Corresponds to priority 10.

Example:

class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(Thread.currentThread().getName() + " with priority " + Thread.currentThread().getPriority() + ": " + i);
        }
    }
}

public class ThreadPriorityExample {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();

        // Set thread priorities
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);

        // Start threads
        thread1.start();
        thread2.start();
    }
}

In this example, thread1 has the minimum priority, and thread2 has the maximum priority. The actual behavior depends on the operating system and the underlying thread scheduler.

Thread Priority Considerations:

  1. Use thread priorities judiciously:
  • Thread priorities should be used carefully as they are platform-dependent and may not guarantee precise behavior across different systems.
  1. Priority Inversion:
  • Be cautious about priority inversion, a situation where a lower-priority thread holds a resource that a higher-priority thread needs. This can lead to unexpected delays.
  1. Thread Priorities and Real-Time Systems:
  • In real-time systems, thread priorities are crucial for meeting timing constraints. However, in general-purpose applications, relying heavily on thread priorities is discouraged.
  1. Scheduling Decisions:
  • Thread priorities are just hints to the scheduler. The scheduler may or may not honor these priorities based on the underlying operating system.
  1. Avoid Excessive Reliance on Priorities:
  • Code should be designed to be correct regardless of thread priorities. Excessive reliance on thread priorities can lead to unpredictable behavior and reduced maintainability.

In summary, while thread priorities can be used to influence scheduling decisions, they should be used cautiously and should not be a primary mechanism for controlling the flow of execution in a program. It’s often more effective to design multithreaded programs with clear synchronization and coordination mechanisms.

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower-priority threads

General form

final void setPriority(int level)

The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread

We can obtain the current priority setting by calling the getPriority( ) method of Thread

final int getPriority( )

Demonstrate thread priorities

class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}

Output

Low-priority thread: 4408112
High-priority thread: 589626904

The higher-priority thread got the majority of the CPU time

Leave a Comment