java : Why the thread priority is not followed when there are more than one print statements in run method?

标签 java multithreading

我正在执行的文件:

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/

相关文章:

c# - 从实例方法调用静态方法线程安全吗?

java - 使用 Java PDFBox 将希伯来语写入 PDF

java - Ant build.xml 中的 Cobertura “unable to locate file”

java - Eclipse类型删除

java - 如果两个相同的对象具有不同的哈希码,有什么缺点

C++ 运行时库设置为/MT,但 api-ms-win*.dll 仍然丢失

java - 对于映射到 java.lang.Class 的列的查询,不支持区分符类型 null

c++ - 为什么Rcout和Rprintf在多线程时会导致堆栈限制错误?

javascript - javascript中实现多线程

multithreading - Hudson SCM 轮询线程在轮询时挂起