Reputation: 207
I executed below code :
public class TestMain extends Thread{
public static Runnable getRunnableObject(){
Runnable r = new Runnable(){
@Override
public void run() {
System.out.println("inside runnable");
}
};
return r;
}
public static void main(String args[]){
Thread t2 = new Thread(getRunnableObject());
// t2.start();
System.out.println("name "+t2.getName()+" id "+t2.getPriority()+" class "+t2.getClass()
+" priortity "+t2.getPriority()+" state "+t2.getState()+" alive/dead "+t2.isAlive());
System.out.println("runtime"+Runtime.getRuntime().availableProcessors());
t2.setPriority(MAX_PRIORITY);
System.out.println(t2.getPriority());
t2.setPriority(MIN_PRIORITY);
System.out.println(t2.getPriority());
t2.setPriority(NORM_PRIORITY);
System.out.println(t2.getPriority());
}
}
Output :
name Thread-0 id 5 class class java.lang.Thread priortity 5 state NEW alive/dead false
runtime4
10
1
5
Now I run it once again uncommenting the code at line 22.
output 2 :
inside runnable
name Thread-0 id 5 class class java.lang.Thread priortity 5 state RUNNABLE alive/dead true
runtime4
5
5
5
Can you tell me why setting the priority is not working when I called start() on the thread ?
Upvotes: 1
Views: 28
Reputation: 30295
It's a race condition.
By the time you're trying to set the priority of t2
, it's already dead.
If you change your Runnable
to block for a while, like this:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("inside runnable");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
//
}
}
}
Then you'll get the same sequence of 10, 1, 5.
Upvotes: 1