Inconsistent output with thread priorities program

Viewed 141

The following program is supposed to show that the thread having higher priority will take up more of the CPU's time. The code is very similar to the one written in The Complete Reference: Java (seventh edition) by Herbert Schildt(Indian Edition) - Page no 237 & 238.

class clicker implements Runnable
{
    long click=0;
    Thread t;
    private volatile boolean running=true;

    public clicker(int p)
    {
        t=new Thread(this,"yo yo");
        t.setPriority(p);
    }

    public void run()
    {
        while(running)
            {click++;}
    }
    public void stop()
    {
        running = false;
    }

    public void start()
    {
        t.start();
    }
}
public class ThreadPriorities {

    public static void main(String[] args) {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        clicker hi=new clicker(Thread.NORM_PRIORITY+2);
        clicker lo=new clicker(Thread.NORM_PRIORITY-2);

        lo.start();
        hi.start();

        try{Thread.sleep(10000);}catch(Exception e){}       

        lo.stop();
        hi.stop();
        try{
            hi.t.join();
            lo.t.join();
        }catch(Exception e){}

        System.out.println("Low priority thread : "+lo.click);
        System.out.println("High priority thread : "+hi.click);
        System.out.println(lo.click<hi.click?true:false);
    }

}

One output:

Low priority thread : 708527884 ; High priority thread : 697458303 ; false

Another output:

Low priority thread : 676775494 ; High priority thread : 687116831; true

What could be the reason for this? I have a Macbook Air, with 4GB RAM. Maybe that could be relevant? Please tell me the reason for these inconsistent outputs. Thanks in advance.

3 Answers
Related