我正在执行的文件:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(MIN_PRIORITY);
m2.setPriority(MAX_PRIORITY);
m1.start();``
m2.start();
}
}
此代码得到的输出是:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:1
running thread priority is:10
而预期的输出是
running thread name is:Thread-1
running thread priority is:10
running thread name is:Thread-0
running thread priority is:1
我的意思是应该首先完全执行具有最高优先级的线程,然后再执行第二个线程,不是吗?这与调度有关吗?
最佳答案
Java 在任何情况下都不保证严格的优先级。看Java Language Specification (2nd Edition) p.445 :
Every thread has a priority. When there is competition for processing resources, threads with higher priority are generally executed in preference to threads with lower priority. Such preference is not, however, a guarantee that the highest priority thread will always be running, and thread priorities cannot be used to reliably implement mutual exclusion.
关于java : Why the thread priority is not followed when there are more than one print statements in run method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358982/