top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Thread Priority in Java

Introduction

In multi-threaded programming, managing the execution order and resource allocation of threads is crucial for optimal performance. Thread priority in Java is fundamental to thread management in this program. By assigning priorities to threads, you can control their relative importance and determine which threads should be executed first when multiple threads compete for system resources.

In this guide, we will explore the thread priority in Java and cover some related topics, including the setter and getter methods and pertinent examples.

Overview

Thread priority in Java is an integer float double long that represents the importance of a thread. Threads with higher priority are more likely to be scheduled for execution before threads with lower priority, although this behavior is not guaranteed. Java provides a range of priorities and offers methods to set and retrieve the priority value of a thread.

What Is Thread Priority?

An integer value from 1 to 10, with 1 being the lowest priority and 10 being the highest, represents thread priority in Java. The default priority assigned to a thread is 5. This range allows for a flexible and scalable approach to prioritizing threads based on their specific requirements.

To set the priority of a thread, you can use the `setPriority()` method provided by the Thread class. This method takes an integer argument representing the desired priority value. Similarly, the `getPriority()` method retrieves the current priority value of a thread.

Setter & Getter Methods of Thread Priority in Java

Java's setter and getter methods for thread priority provide a means to assign and retrieve a thread's priority value. These methods permit dynamic manipulation of a thread's priority during runtime as well as the retrieval of information about the current priority setting. 

Here are the main features of these techniques involving thread priority in Java:

1. setPriority(integer priority):

   - Signature of the Method: 'public final void setPriority(int priority)'

   - Description: This method sets the priority of a thread to the integer value specified.

   - Descriptive Traits:

     - An integer argument representing the intended priority value is accepted.

     - Valid priority values range between 1 (minimum priority) and 10 (maximum priority).

     - If an invalid priority value (outside the valid range) is provided, the method will raise a 'IllegalArgumentException'.

     - This method is 'final', indicating subclasses cannot override it.

     - Once the priority is set, it remains in effect until it is explicitly altered using'setPriority()' once more.

     - The method can be invoked on an instance of the class 'Thread' or any of its subclasses.

2. getPriority():

   - Method Signature: 'public final integer getPriority()'

   - Description: This method retrieves the current thread priority.

   - Descriptive Traits:

     It returns an integer value representing the thread's current priority.

     - The returned value will fall within the legitimate priority value range (1 to 10).

     - If no explicit priority is specified for the thread, this function returns the default priority value, represented by the 'NORM_PRIORITY' constant (5).

     - This method is 'final', indicating subclasses cannot override it.

     - An instance of the 'Thread' class or any of its subclasses may invoke this method.

These setter and getter methods facilitate manipulating and retrieving information regarding a thread's priority. They enable dynamic control over the scheduling behavior of threads and allow you to fine-tune the execution order based on the relative importance of various threads within your application.

To illustrate the setter and getter methods of thread priority, consider the following example:

In this example, a new thread is created, and its priority is set to 7 using the `setPriority()` method. The `getPriority()` method is then used to retrieve the priority value, which is subsequently printed to the console. In this case, the output will be:

Here, the thread priority is set to 7, and the `getPriority()` method confirms the assigned priority.

3 Constants Defined in Thread Class

The Thread class in Java provides three constants related to thread priority: `MIN_PRIORITY`, `NORM_PRIORITY`, and `MAX_PRIORITY`. These constants are predefined values representing the minimum, default, and maximum thread priorities.

- `MIN_PRIORITY`: This constant has a value of 1, representing the lowest possible thread priority.

- `NORM_PRIORITY`: With a value of 5, this constant represents the default priority assigned to threads if no priority is explicitly set.

- `MAX_PRIORITY`: This constant is set to 10, indicating the highest possible thread priority.

To understand these constants, consider the following example:

The output of this example will be:

Here, we use `System.out.println()` to display the values of the constants. The output shows the predefined values for the minimum, default, and maximum thread priorities.

Thread priority example in Java

Let's consider a practical example of thread priority in Java to understand how thread priority influences thread execution. Suppose we have two threads, `ThreadA` and `ThreadB`, with priorities set to 8 and 3, respectively. 

In this scenario, `ThreadA` has a higher priority than `ThreadB`. However, it's important to note that thread priority only hints at the underlying operating system scheduler and may not always result in the expected execution order. The actual behavior depends on various factors, including the operating system and the system's workload.

Example of IllegalArgumentException

The `setPriority()` method in Java may throw an `IllegalArgumentException` if an invalid priority value is provided. Let's consider an example:

In this case, since the value 15 exceeds the valid range of thread priorities (1-10), the `setPriority()` method will throw an `IllegalArgumentException`.

Example to Understand Thread Priority in Java 

To further clarify the behavior of thread priorities in Java, let's explore an example where multiple threads with different priorities are created and executed.

In this example, three threads (`thread1`, `thread2`, and `thread3`) are created and assigned different priorities. The `run()` method of the `MyThread` class prints the priority of each thread when it is executed.

The output of this example will vary based on the underlying system and its scheduler. However, assuming the threads start and complete their execution, the output may look like this:

Here, the threads are executed in the order specified by their priorities. However, it's important to note that the actual execution order may differ due to factors such as the operating system's scheduling algorithm and the system's workload.

Example to Create Custom Thread with User-defined Name and Priority

To demonstrate how to create a custom thread with a user-defined name and priority, consider the following example:

In this example, a `CustomThread` class is created, which extends the `Thread` class. The constructor of `CustomThread` accepts a name and priority as parameters, which are used to set the name and priority of the thread. The `run()` method of the `CustomThread` class prints the name and priority of the thread when it is executed.

The output of this example will be:

Here, we create two instances of the `CustomThread` class, `thread1` and `thread2`, with different names and priorities. The output shows that each thread executes with its respective name and priority.

Thread priority C++ highlights:

A multi-threaded C++ program's thread priority determines its scheduling priority. Prioritizing threads helps regulate execution and resource allocation.

Thread priorities: C++ threads have priority values. The operating system and threading library affect the priority value range and interpretation.

Scheduling Policies: Operating systems use round-robin or priority-based scheduling to prioritize thread execution. These policies help the scheduler allot CPU time and resources to threads.

Thread Priority: Most threading libraries allow thread priority setting. These methods normally take a priority argument. Platform-specific priority levels vary.

Default Priorities: If none is set, the operating system or threading library may assign a default priority to each thread. Threads created without a priority level using the default priority.

Thread creation: Developers can set thread priority when building them. This lets the application manage threads with varying priorities.

Priority inheritance: Priority inheritance in some threading libraries boosts a thread's priority while it waits for a resource held by a lower-priority thread. This prevents priority inversion and ensures higher-priority threads get resources quickly.

Platform-Dependence: Thread priority behavior varies by the operating system and threading library. Developers should review platform-specific documentation to understand thread priority implementation on their target platform.

The operating system's scheduling mechanism, CPU availability, and system workload can affect thread priority and the ultimate execution order. Thread priority should be carefully considered based on application needs and system behavior.

Conclusion

To summarize, thread priority in Java allows you to control the threads' scheduling and resource allocation in a multi-threaded program. Developers can indicate the relative importance of threads and regulate their execution order by assigning priority to them. 

However, it is crucial to remember that thread priority does not ensure a precise execution order, as it is determined by the underlying operating system's scheduler and other considerations. Thread priority should be handled with caution, considering the application's specific requirements and the system's behavior.

Thread priority in Java is useful in a variety of situations. It can be used to maintain a responsive user interface, prioritize real-time processing, properly allocate resources, coordinate thread execution, and effectively handle background operations. Developers may create multi-threaded programs that are efficient, responsive, and optimized for specific job requirements by understanding thread priority and its ramifications.

FAQs

1. What is thread priority in Java?

Java thread priority is an integer property of threads that determines the order in which threads are scheduled for execution. This priority is the lowest value of a thread and the highest value of a thread. By default, every thread is given a priority of 5 (NORM_PRIORITY). The Java runtime system uses a thread priority to determine when one thread should be switched to another. 

2. Are there any risks or disadvantages associated with manipulating thread priorities in Java?

There are certain risks involved in manipulating thread priorities. In some cases, high-priority threads can monopolize the CPU time, leading to a situation called "starvation", where lower-priority threads do not get a chance to run. This can lead to unpredictable behavior or performance issues.

3. What is the default priority of a thread in Java?

The default priority of a thread in Java is represented by the constant `NORM_PRIORITY`, which has a value of 5.

Leave a Reply

Your email address will not be published. Required fields are marked *