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

我使用线程优先级创建了一个程序,我获得了优先级为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 

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

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

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