Java – Understanding “priority” in java threads

javamultithreading

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…

Best Answer

Thread priority in Java does not guarantee the intended behavior. It is just like a hint to the JVM. The actual behavior depends on the underlying OS.

Also, read this nice little para about Cooperative vs. Preemptive Threading: http://www.cafeaulait.org/course/week11/32.html