Java setPriority() 是什么意思?

Java setPriority() what does it mean?

我对 Thread.setPriority 的作用感到困惑。无论我设置什么优先级,都没有关系,它仍然是先运行程序名,然后再启动。

谁能给我解释一下这里发生了什么?

class Main {
    public static void main(String[ ] args) {
        
        Name name = new Name();
        name.setPriority(2);
        
        Welcome welcome = new Welcome();
        welcome.setPriority(7);
        name.start();
        welcome.start();
    }
}

class Welcome extends Thread{
    public void run() {
        System.out.println("Welcome!");
    }
}

class Name extends Thread{
    public void run() {
        System.out.println("Please enter your name");
    }
}

Thread.setPriority不设置线程的执行顺序,而是帮助线程调度器决定在分配 CPU.

我认为这个 解释得很好:

The method setPriority can be used to give the current thread object on which you are calling this method a priority. This priority is used by the thread scheduler of your OS to give the threads CPU time based on their priorities. So a thread with higher priority is more likely to get CPU time than one with a smaller priority.

setPriority()只在线程组内有效。两种情况:

  • 如果设置的优先级高于组的当前最大优先级,线程将设置为组的当前最大安全性(Thread.MAX_PRIORITY)
  • 否则采用设置优先级

并通过本地方法设置

private native void setPriority0(int newPriority);