Thread priority does not work as expected?

812 views Asked by At

i made a program using Thread priority and i got the same number of clicks for both thread with priority 1 and thread with priority 10 , its confusing why i am getting this

class clicker implements Runnable {
    int click = 0;
    Thread t;
    private volatile boolean running = true;
    public clicker(int p) {
        t = new Thread(this);
        t.setPriority(p);
    }
    public void run() {
        while (running) {
            click++;
        }
    }
    public void stop() {
        running = false;
    }
    public void start() {
        t.start();
    }
}

class hilopri {
    public static void main(String args[]) {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        clicker hi = new clicker(1);
        clicker lo = new clicker(10);
        lo.start();
        hi.start();
        try {
            Thread.sleep(10000);
        } 
        catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        lo.stop();
        hi.stop();
        // Wait for child threads to terminate.
        try {
            hi.t.join();
            lo.t.join();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught");
        }
        System.out.println("Low-priority thread: " + lo.click);
        System.out.println("High-priority thread: " + hi.click);
    }
}

the output is almost the same regardless of the priority

Low-priority thread: 322141133
High-priority thread: 477591649
2

There are 2 answers

0
TheLostMind On

Actually, the behavior of Thread Priority isn't guaranteed. Changing the priority is just a hint / suggestion to the underlying OS that can be totally ignored. A thread with low priority can get more CPU cycles than a thread with high priority. So, bottom line- don't write critical code based on Thread priority.

0
Solomon Slow On

What @TheLostMind told you is all true, but here's something else to consider.

If your computer has more CPUs than you have runnable threads, then all of the runnable threads are going to be allowed to run. Priority (if it matters at all) can only matter when the threads are in contention for a scarce resource.