Every thread has a priority assigned to it. Thread priority in Java has the effect of controlling the flow of program. Here I will describe Java thread priorities and also share same code for defining priorities to Java threads.
Since with the use of multi threading, there is no defined order in which the threads will execute. But Java provides few mechanisms by using which one can control the execution of multiple threads to some extent and assign thread priorities to them.
In Java, threads can have three level of priorities viz:
1) Min Priority 2) Normal Priority 3) High Priority
One can assign priority to a thread in Java by using the setPriority() method. One important point to note about thread priorities in Java is that it is not guaranteed that a thread with higher priority will always get preference for execution than a thread with lower priority. It all depends upon the thread scheduler to decide which thread to execute currently.
The use of assigning priority to a Java thread is that it is just a hint to thread scheduler to decide which thread is more important for execution and hence give more preference to that thread.
Thread Priorities Example code:
package com.example;
public class MyClass extends Thread{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) throws Exception {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
t1.setName("Thread 1");
t2.setName("Thread 2");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
Output:
Thread 2 or Thread 1
Thread 1 Thread 2
Conclusion and Analysis
Out of every 10 times I execute the above code, Thread 2 gets executed before Thread 1 8 times and the reverse happens only 2 times.
Moreover, if I don’t assign thread priorities in the above code then out of every 10 times, Thread 1 gets executed before Thread 2.
This clearly indicates that assigning a higher priority to a thread does make it more likely that the higher priority thread will get executed before low priority thread. Again, the above statement may not always be true.
1 comments:
Thanks Swati for sharing the knowledge.
I would like to add here that we can also use integer values in the range of 1 to 10 in setPriority() method. Thread.MIN_PRIORITY has value 1, Thread.NORM_PRIORITY has value 5, and Thread.MAX_PRIORITY has value 10. If we have more threads to control then we can assign priority levels from 1 to 10.
If we have more than one threads with the same priority then the thread schedular can pickup any thread out of those threads and schedule for execution.
Thanks again.
Hitesh Patel
Post a Comment