I am new to the world of java and threads..I was just going through an example code as below:-
package com.alice.learnthread;
class NewThread implements Runnable{
Thread t;
long clicker=0;
private volatile boolean running=true;
NewThread(int p){
t=new Thread(this);
t.setPriority(p);
}
public void run(){
while(running){
clicker++;
}
}
public void stop(){
running=false;
}
public void start(){
t.start();
}
}
public class TestThread {
public static void main(String[] args){
Thread r=Thread.currentThread();
r.setPriority(Thread.MAX_PRIORITY);
NewThread hi=new NewThread(Thread.NORM_PRIORITY+2);
NewThread lo=new NewThread(Thread.NORM_PRIORITY-2);
hi.start();
lo.start();
try{
r.sleep(5000);
}catch(InterruptedException e){
System.out.println("caught");
}
hi.stop();
lo.stop();
try{
hi.t.join();
lo.t.join();
}catch(InterruptedException e){
System.out.println("cau1");
}
System.out.println("hi = "+hi.clicker+" lo="+lo.clicker);
}
}
However according to the output in the book the thread with high priority should have higher value for the variable clicker. But in my case the values for the variable clicker is much higher for the lower priority thread than for the higher priority one.The output is like below for me:-
hi = 2198713135 lo=2484053552
Does this not mean that lower priority thread got more CPU time than the higher priority one…Am i missing something..The results are the same(higher clicker value for the lower priority thread) on both ubuntu and win7…
As sul said, priority is more a hint than a contract to the JVM.
In your case, your result can be explained by several theories:
That is just some facts to say that how thread act is unpredictable. For example try to start the low priority thread first and I am sure you will have a different result.
Also, try this :
I am sure that removing the volatile variable and changing how the thread is stopped will give you an other result.