Home » Java Thread setPriority() Method with Examples

Java Thread setPriority() Method with Examples

by Online Tutorials Library

Java Thread setPriority() method

The setPriority() method of thread class is used to change the thread’s priority. Every thread has a priority which is represented by the integer number between 1 to 10.

Thread class provides 3 constant properties:

  1. public static int MIN_PRIORITY: It is the maximum priority of a thread. The value of it is 1.
  2. public static int NORM_PRIORITY: It is the normal priority of a thread. The value of it is 5.
  3. public static int MAX_PRIORITY: It is the minimum priority of a thread. The value of it is 10.

We can also set the priority of thread between 1 to 10. This priority is known as custom priority or user defined priority.

Syntax

Parameter

a: It is the priority to set this thread to.

Return

It does not return any value.

Exception

IllegalArgumentException: This exception throws if the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.

SecurityException: This exception throws if the current thread cannot modify this thread.

Example 1: Maximum Priority Thread

Test it Now

Output:

Priority of thread is: 10  

Example 2: Minimum Priority Thread

Test it Now

Output:

Priority of thread is: 1  

Example 3: Normal Priority Thread

Test it Now

Output:

Priority of thread is: 5  

Example 4: User define Priority Thread

Test it Now

Output:

Priority of thread t1 is: 4  Priority of thread t2 is: 7  running...  

Example 5: When priority is greater than 10

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException  at java.lang.Thread.setPriority(Thread.java:1089)  at JavaSetPriorityExp5.main(JavaSetPriorityExp5.java:13)  

You may also like