Can anybody explain how thread priority works in java. The confusion here is if java does'nt guarantee the implementation of the Thread
according to its priority then why is this setpriority()
function used for.
My code is as follows :
public class ThreadSynchronization implements Runnable{
public synchronized void run() {
System.out.println("Starting Implementation of Thread "+Thread.currentThread().getName());
for(int i=0;i<10;i++)
{
System.out.println("Thread "+Thread.currentThread().getName()+" value : "+i);
}
System.out.println("Ending Implementation of Thread "+Thread.currentThread().getName());
}
public static void main(String[] args) {
System.out.println("Program starts...");
ThreadSynchronization th1 = new ThreadSynchronization();
Thread t1 = new Thread(th1);
t1.setPriority(1);
synchronized(t1)
{
t1.start();
}
ThreadSynchronization th2 = new ThreadSynchronization();
Thread t2 = new Thread(th2);
t2.setPriority(9);
synchronized (t2) {
t2.start();
}
System.out.println("Program ends...");
}
}
In the above program even if I change the priority I find no difference in the output. Also a real time application of how thread priority can be used would be of great help. Thanks.
Thread priority is just a hint to OS task scheduler and is dependent on the underlying OS. OS will try to allocate more resources to a high priority thread but it does not guarantee it. So if your program is dependent on thread priorities than you are in-turn binding your program to underlying OS, which is bad.
From Java Concurrency in Practice:
Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.