Thread priority does not work as expected?

好久不见. 提交于 2019-12-02 07:00:12

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27142551/thread-priority-does-not-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!