I gave thread 1 high priority and thread 2 low priority.
Now, when I executed the code. Thread one will go to sleep for 500ms then thread two is called and it will also go to 500 ms sleep.
Once t1 and t2 woke up, let's assume because of some system error both woke up at the same time. The thread with MAX_PRIORITY should run first. But, here why t2 is running?
*sometimes t1 will run and some times t2 will run there is no guarantee
public class JavaThread_priority_name {
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run(){
for (int i = 0; i < 5; i++) {
try {Thread.sleep(500);} catch (Exception e) {e.printStackTrace();}
System.out.print("High -> " + (i+1));
}
}
};
Thread t2 = new Thread(){
public void run(){
for (int i = 0; i < 5; i++) {
try {Thread.sleep(500);} catch (Exception e) {e.printStackTrace();}
System.out.println("Low -> " + (i+1));
}
}
};
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
output
Low -> 1
High -> 1
Low -> 2
High -> 2
Low -> 3
High -> 3
High -> 4
Low -> 4
Low -> 5
High -> 5