线程优先级不能按预期工作?

时间:2014-11-26 06:19:04

标签: java multithreading interface thread-priority

我使用线程优先级创建了一个程序,我获得了优先级为1的线程和优先级为10的线程的相同点击次数,这让我很困惑为什么我会得到这个

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);
    }
}
无论优先级

,输出几乎相同
Low-priority thread: 322141133
High-priority thread: 477591649

2 个答案:

答案 0 :(得分:1)

实际上,无法保证线程优先级的行为。更改优先级只是对底层操作系统的提示/建议,可以完全忽略。具有低优先级的线程可以获得比具有高优先级的线程更多的CPU周期。所以,底线 - 不要根据线程优先级编写关键代码。

答案 1 :(得分:0)

@TheLostMind告诉你的是真的,但这里还有别的东西要考虑。

如果您的计算机拥有的CPU数量超过了可运行线程数,那么可以运行所有的可运行线程。优先级(如果有意义的话)只有在线程争用稀缺资源时才有意义。