0
Thread priority does not work properly
class Loader extends Thread { int i=0; Loader(int j){ this.i = j; } public void run() { System.out.println("Hello "+i); } } class MyClass { public static void main(String[ ] args) { Loader obj = new Loader(1); Loader obj2 = new Loader(2); Loader obj3 = new Loader(3); obj3.setPriority(10); obj.setPriority(2); obj2.setPriority(1); obj3.start(); obj.start();obj2.start(); } } Output should be hello 3,hello 1,hello 2. But sometimes it gives different output like hello 1,hello 2,hello 3
1 Antwort
+ 2
Thread priority will affect threads execution only when there are multiple threads comes to executes at same for processor time. And then highest priority thread get executed.
It is not mean to set order of execution always.
In your code, you started obj3.start()
then after obj, obj2
It may start in sequence as obj3, obj1, obj2.
But may run and completed as in sequences started.
The output may not always be same as it also depends upon the thread scheduler, the priority of a thread only tells the thread scheduler as request of order, but it relies on he thread scheduler.
Edit:
Rule of thumb:
At any given time, the highest priority thread is run. However, this is not guaranteed. It depends the thread scheduler. For this reason, use priority only to affect scheduling policy for efficiency purposes. Do not rely on thread priority for algorithm correctness.
http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/priority.html