Java - Properties of the Thread Class

Learn: What do you understand by Thread Priority in java? Explain in brief Thread Priorities in java. By Preeti Jain Last updated : March 23, 2024

Properties of the Thread Class

  • Thread Priorities determines how a thread should be treated with respect to others.
  • Several threads executes concurrently. Every thread has some priority.
  • Which thread will get a chance first to execute it is decided by thread scheduler based on thread priority.
  • The valid range of thread priority is 1 to 10​ ​(i.e. 1,2,3,4.....10.) and 1 is the min priority and 10 is the max priority.
  • We can also represent thread priority in terms of constants. Basically, we have three types of constants like MIN_PRIORITY, MAX_PRIORITY, NORM_PRIORITY.

Syntax

Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
Thread.MAX_PRIORITY 
  • ​Every thread has some priority and it can be defined by JVM or user (i.e. if not defined by the user then JVM will set default priority).
  • Thread having high priority will get a chance first to execute and threads having same priority then we can't expect exact execution order any thread can get a chance.

Setting Properties of Thread Class

To set a property, the setPriority() method is used.

Example

class SetPriority {
  public static void main(String[] args) {
    System.out.println("Before setting Priority of Main thread is " +
      Thread.currentThread().getPriority());
    
    Thread.currentThread().setPriority(6);
    
    System.out.println(" After setting Priority of Main thread is " +
      Thread.currentThread().getPriority());
  }
}

Output

D:\Java Articles>java SetPriority
Before setting Priority of Main thread is 5
After setting Priority of Main thread is 6

Getting Properties of Thread Class

To set a property, the getPriority() method is used.

Example

class GetPriority {
  public static void main(String[] args) {
    System.out.println("Priority of Main thread is " +
      Thread.currentThread().getPriority());
  }
}

Output

D:\Java Articles>java GetPriority
Priority of Main thread is 5

Comments and Discussions!

Load comments ↻





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