Example:
class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
public void run(){
for (int i=0; i<5; i++) {
System.out.println(Thread.currentThread().getName()
+"("+Thread.currentThread().getPriority()+ ")"
+", loop "+i);
}
}
};
public class Demo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()
+"("+Thread.currentThread().getPriority()+ ")");
Thread t1=new MyThread("t1"); // t1
Thread t2=new MyThread("t2"); // t2
t1.setPriority(1); // t1 priority 1
t2.setPriority(10); //t2 priority 10
t1.start(); // start t1
t2.start(); // start t2
}
}
When I execute the program, some times I have the output like below:
//Output1
main(5)
t2(10), loop 0
t2(10), loop 1
t2(10), loop 2
t2(10), loop 3
t2(10), loop 4
t1(1), loop 0
t1(1), loop 1
t1(1), loop 2
t1(1), loop 3
t1(1), loop 4
Sometimes I have output like below:
//Output2
main(5)
t1(1), loop 0
t1(1), loop 1
t1(1), loop 2
t1(1), loop 3
t1(1), loop 4
t2(10), loop 0
t2(10), loop 1
t2(10), loop 2
t2(10), loop 3
t2(10), loop 4
In some other occasions I have output where t1 starts first, and t2 starts before t1 completes all output.
I thought output1
makes more sense as “Threads with higher priority are executed in preference to threads with lower priority.”
How can we understand the reasoning behind this example?
As you already mentioned in your post:
“Threads with higher priority are executed in preference to threads with lower priority.”
This does mean, that a thread with higher priority has a higher likeliness of being executed than a low-priority-thread. It doesn't mean that a thread with higher priority will always be executed first/finish first. The actual thread-handling depends upon the OS (java simply uses the thread-libraries provided by the OS it runs on).
Your lower-prioritized thread is started first, therefore it may in some cases complete even before the higher-prioritized even starts. 5 iterations is not that much. On my (Windows) machine, if I replace the number of iterations with 100, the higher-prioritized thread is consistently selected first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With