Home » Java programming language

Java Thread Class final void setPriority(int priority) method with Example

Java Thread Class final void setPriority(int priority) method: Here, we are going to learn about the final void setPriority(int priority) method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 31, 2019

Thread Class final void setPriority(int priority)

  • This method is available in package java.lang.Thread.setPriority(int priority).
  • This method is used to set the priority of this thread.
  • This method is not static so this method is accessible with Thread class object it is not accessible with the class name.
  • This method is final so we can't override this method in our program.
  • The return type of this method is void so it does not return anything.
  • This method does not raise any exception.
  • We need to notice that if we don't assign any priority explicitly the default priority of this thread is 5.
  • Priority range will lie between 1 and 10 and 1 is the min_priority and 10 is the max_priority of a thread.

Syntax:

    final void setPriority(int priority){
    }

Parameter(s):

We pass only one object as a parameter in the method of the Thread and the parameter is the priority of this thread too.

Return value:

The return type of this method is void, it does not return anything.

Java program to demonstrate example of setPriority() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/

import java.lang.Thread;

class SetThreadPriority extends Thread {
    // Override run() of Thread class
    public void run() {
        System.out.println("Thread Name : " + Thread.currentThread().getName());
        System.out.println("Current thread priority is : " + Thread.currentThread().getPriority());
        // By using setPriority() method is used to change 
        // the priority of this thread
        Thread.currentThread().setPriority(6);
        System.out.println("New thread priority is : " + Thread.currentThread().getPriority());
    }

    public static void main(String[] args) {
        // Creating an object of SetThreadPriority class
        SetThreadPriority st_priority = new SetThreadPriority();

        // We are setting the name of the thread GetThreadPriority
        st_priority.setName("SetThreadPriority");

        // Calling start() method with SetThreadPriority class 
        // object of Thread class
        st_priority.start();
    }
}

Output

E:\Programs>javac SetThreadPriority.java

E:\Programs>java SetThreadPriority
Thread Name : SetThreadPriority
Current thread priority is : 5
New thread priority is : 6


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.