The Wayback Machine - https://web.archive.org/web/20240903034648/https://www.geeksforgeeks.org/java-thread-priority-multithreading/
Open In App

Java Thread Priority in Multithreading

Last Updated : 19 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by the programmer explicitly. 

Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. 

  • The default priority is set to 5 as excepted.
  • Minimum priority is set to 1.
  • Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:

  1. public static int NORM_PRIORITY
  2. public static int MIN_PRIORITY
  3. public static int MAX_PRIORITY

Let us discuss it with an example to get how internally the work is getting executed. Here we will be using the knowledge gathered above as follows:

  • We will use currentThread() method to get the name of the current thread. User can also use setName() method if he/she wants to make names of thread as per choice for understanding purposes.
  • getName() method will be used to get the name of the thread.

The accepted value of priority for a thread is in the range of 1 to 10. 

Let us do discuss how to get and set priority of a thread in java. 

  1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
  2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and maximum(10) limit.

Example 

Java




// Java Program to Illustrate Priorities in Multithreading
// via help of getPriority() and setPriority() method
 
// Importing required classes
import java.lang.*;
 
// Main class
class ThreadDemo extends Thread {
 
    // Method 1
    // run() method for the thread that is called
    // as soon as start() is invoked for thread in main()
    public void run()
    {
        // Print statement
        System.out.println("Inside run method");
    }
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating random threads
        // with the help of above class
        ThreadDemo t1 = new ThreadDemo();
        ThreadDemo t2 = new ThreadDemo();
        ThreadDemo t3 = new ThreadDemo();
 
        // Thread 1
        // Display the priority of above thread
        // using getPriority() method
        System.out.println("t1 thread priority : "
                           + t1.getPriority());
 
        // Thread 1
        // Display the priority of above thread
        System.out.println("t2 thread priority : "
                           + t2.getPriority());
 
        // Thread 3
        System.out.println("t3 thread priority : "
                           + t3.getPriority());
 
        // Setting priorities of above threads by
        // passing integer arguments
        t1.setPriority(2);
        t2.setPriority(5);
        t3.setPriority(8);
 
        // t3.setPriority(21); will throw
        // IllegalArgumentException
 
        // 2
        System.out.println("t1 thread priority : "
                           + t1.getPriority());
 
        // 5
        System.out.println("t2 thread priority : "
                           + t2.getPriority());
 
        // 8
        System.out.println("t3 thread priority : "
                           + t3.getPriority());
 
        // Main thread
 
        // Displays the name of
        // currently executing Thread
        System.out.println(
            "Currently Executing Thread : "
            + Thread.currentThread().getName());
 
        System.out.println(
            "Main thread priority : "
            + Thread.currentThread().getPriority());
 
        // Main thread priority is set to 10
        Thread.currentThread().setPriority(10);
 
        System.out.println(
            "Main thread priority : "
            + Thread.currentThread().getPriority());
    }
}


Output

t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10

 Output explanation:

  • Thread with the highest priority will get an execution chance prior to other threads. Suppose there are 3 threads t1, t2, and t3 with priorities 4, 6, and 1. So, thread t2 will execute first based on maximum priority 6 after that t1 will execute and then t3.
  • The default priority for the main thread is always 5, it can be changed later. The default priority for all other threads depends on the priority of the parent thread.

Now geeks you must be wondering out what if we do assign the same priorities to threads then what will happen. All the processing in order to look after threads is carried with help of the thread scheduler. One can refer to the below example of what will happen if the priorities are set to the same and later onwards we will discuss it as an output explanation to have a better understanding conceptually and practically.

Example 

Java




// Java program to demonstrate that a Child thread
// Getting Same Priority as Parent thread
 
// Importing all classes from java.lang package
import java.lang.*;
 
// Main class
// ThreadDemo
// Extending Thread class
class GFG extends Thread {
 
    // Method 1
    // run() method for the thread that is
    // invoked as threads are started
    public void run()
    {
        // Print statement
        System.out.println("Inside run method");
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // main thread priority is set to 6 now
        Thread.currentThread().setPriority(6);
 
        // Current thread is accessed
        // using currentThread() method
 
        // Print and display main thread priority
        // using getPriority() method of Thread class
        System.out.println(
            "main thread priority : "
            + Thread.currentThread().getPriority());
 
        // Creating a thread by creating object inside
        // main()
        GFG t1 = new GFG();
 
        // t1 thread is child of main thread
        // so t1 thread will also have priority 6
 
        // Print and display priority of current thread
        System.out.println("t1 thread priority : "
                           + t1.getPriority());
    }
}


Output

main thread priority : 6
t1 thread priority : 6

 Output explanation:

  • If two threads have the same priority then we can’t expect which thread will execute first. It depends on the thread scheduler’s algorithm(Round-Robin, First Come First Serve, etc)
  • If we are using thread priority for thread scheduling then we should always keep in mind that the underlying platform should provide support for scheduling based on thread priority.

All this processing is been carried over with the help of a thread scheduler which can be better visualized withthe help of a video sample been provided below as follows:



Previous Article
Next Article

Similar Reads

Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated After JDK 1.1 Version?
The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. There are many methods in Thread Class but some of them are deprecated as of JDK 1.1. In this article, we will understand the reason behind it. Deprecated methods are those that are no long
5 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no
3 min read
Naming a thread and fetching name of current thread in Java
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. Methods: There are two ways by which we c
5 min read
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : Extending the Thread class Implementing the Runnable InterfaceThre
3 min read
What does start() function do in multithreading in Java?
We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden run() function? Why always the start function is cal
2 min read
Deadlock in Java Multithreading
synchronized keyword is used to make the class or method thread-safe which means only one thread can have the lock of the synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.  It is important to use if our program is running in a multi-threaded environment where two or more threads
7 min read
Java Multithreading Interview Questions and Answers
Java Multithreading is a fundamental aspect of the Java programming language, enabling developers to create applications that can perform multiple tasks simultaneously, thus improving performance and responsiveness. Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion de
13 min read
Java.lang.Thread Class in Java
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of threads by providing constructors and methods to p
8 min read
MultiThreading in Android with Examples
Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equivalent number of threads are available. For example
3 min read
Daemon Thread in Java
In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon t
4 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same shared memory This communication in multithreading ca
5 min read
Lock framework vs Thread synchronization in Java
Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackl
5 min read
Thread Safety and how to achieve it in Java
As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on
5 min read
How to Create a Thread-Safe ConcurrentHashSet in Java?
Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supported by ConcurrentHashMap. ConcurrentHashSet can be c
4 min read
Thread.sleep() Method in Java With Examples
Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. The sleep() method is used to stop the execution of
4 min read
Importance of Thread Synchronization in Java
Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes are running and within a process, multiple threads
10 min read
How Does ConcurrentHashMap Achieve Thread-Safety in Java?
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class ConcurrentHashMap<K,V> extends AbstractMap<
6 min read
run() Method in Java Thread
The run() method is available in the thread class constructed using a separate Runnable object. Otherwise, this method does nothing and returns. We can call the run() method multiple times. The run() method can be called in two ways which are as follows: Using the start() method.Using the run() method itself. Syntax: public void run() { //statement
3 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Which Method Should We Use to Release a Lock from a Thread in Java?
In JVM we have the option of multithreading. It is an act of executing a complex process using virtual processing entities independent of each other. These entities are called threads. A thread gets blocked if it can't get access to the synchronized block. The Lock API provides the tryLock() method. The thread acquires a lock only if it's available
5 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running immediately. This is usually called the main thread
4 min read
Thread Pools in Java
Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service this new request in the newly created thread. Whil
9 min read
Implement Runnable vs Extend Thread in Java
As discussed in Java multi-threading article we can define a thread in the following two ways: By extending Thread class By implementing Runnable interface In the first approach, Our class always extends Thread class. There is no chance of extending any other class. Hence we are missing Inheritance benefits. In the second approach, while implementi
2 min read
Thread isAlive() Method in Java With Examples
Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of isAlive() and join() method.One thread gets to know when another thread has ended. Let us do depict stages of the lifecycle o
2 min read
Interrupting a Thread in Java
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt
3 min read
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any instant in time. Life Cycle of a Thread There are mult
6 min read
Inter-thread Communication in Java
Prerequisite: Multithreading in Java, Synchronized in Java  Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. Note: Inter-thread communication is also known as Cooperation in Java. What is Polling
6 min read
Priority Queue in Reverse Order in Java
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap.
4 min read
Unit Testing, Integration Testing, Priority Testing using TestNG in Java
TestNG is an automated testing framework. In this tutorial, let us explore more about how it can be used in a software lifecycle. Unit Testing Instead of testing the whole program, testing the code at the class level, method level, etc., is called Unit Testing The code has to be split into separate classes and methods so that testing can be carried
6 min read
Servlet - Single Thread Model Interface
Single Thread Model Interface was designed to guarantee that only one thread is executed at a time in a given servlet instance service method. It should be implemented to ensure that the servlet can handle only one request at a time. It is a marker interface and has no methods. Once the interface is implemented the system guarantees that there's ne
3 min read
Article Tags :
Practice Tags :