‹‹ Previous
Next ››
setPriority() method of thread
- setPriority() method is used to set the priority of a thread. A priority can be set from number 1 to 10. Java provides three constants to represent priority.
Syntax
public final void setPriority(int priority)
- Three constants which are used for priority are:
- (i) public static in MIN_PRIORITY :- Its value is 1 and denotes minimum priority.
- (ii) public static int NORM_PRIORITY:- It is default priority. Its value is 5.
- (iii) public static int MAX_PRIORITY:- It is maximum priority. Its value is 10.
- setPriority() raises following exceptions:
- (i) IllegalArgumenttException :- If priority is not between 1 (MIN_PRIORITY) and 10 (MAX_PRIORITY) then this exception is raised.
- (ii) SecurityException :- This exception is raised when priority can not be modified.
Example
public class Exp1 extends Thread {
public void run() {
System.out.println("Priority of " + Thread.currentThread().getName() + " is " + Thread.currentThread().getPriority());
}
public static void main(String args[]) {
Exp1 t0 = new Exp1();
Exp1 t1 = new Exp1();
Exp1 t2 = new Exp1();
Exp1 t3 = new Exp1();
t0.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.NORM_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(7);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
Output
Output will vary in each run
Priority of Thread-2 is 1
Priority of Thread-0 is 10
Priority of Thread-3 is 7
Priority of Thread-1 is 5
‹‹ Previous
Next ››