C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Thread properties in java

Learn: What do you understand by Thread Priority in java? Explain in brief Thread Priorities in java.
Submitted by Preeti Jain, on February 07, 2018

Thread priorities

  • 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.
  • How can we set the priority of a thread we will see in below example,

1) By setPriority (int p):

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

How can we get priority of a thread? We will see in below examples...

2) By getPriority ():

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

Read more...

  1. Explain life cycle of a thread in java.
  2. How to Create Java Threads (java examples to create threads)?
  3. Thread Synchronisation in Java with Example.
  4. Java program to demonstrate example of thread.
  5. Java program to Join Threads.


Liked this article? Do share with your friends :)


COMMENTS