我已按以下顺序设置线程的优先级
A 然后 B 然后 C 。但是当我运行下面的程序时,有时 B 在 A 之前运行。 我不明白这个执行,因为我将 B 的优先级设置为低于 A 的优先级。
public class AThread implements Runnable{
public void run(){
System.out.println("In thread A");
}}
public class BThread implements Runnable {
public void run(){
System.out.println("In thread B");
}
}
public class CThread implements Runnable {
public void run(){
System.out.println("In thread C");
}
}
public class ThreadPriorityDemo {
public static void main(String args[]){
AThread A = new AThread();
Thread tA = new Thread(A);
BThread B = new BThread();
Thread tB = new Thread(B);
CThread C = new CThread();
Thread tC = new Thread(C);
tA.setPriority(Thread.MAX_PRIORITY);
tC.setPriority(Thread.MIN_PRIORITY);
tB.setPriority(tA.getPriority() -1);
System.out.println("A started");
tA.start();
System.out.println("B started");
tB.start();
System.out.println("C started");
tC.start();
}
}
最佳答案
线程优先级可能不是您想象的那样。
线程的优先级是对操作系统的建议,在涉及这两个线程的任何调度或 CPU 分配决策点中优先选择一个线程。但如何实现取决于操作系统和 JVM 实现。
JavaMex对线程优先级进行了很好的讨论。要点是:
- 优先级可能根本没有任何影响。
- 优先级只是决定调度的计算的一部分。
- 不同的 Java 优先级值在实践中可能会转换为相同的值(例如,优先级 10 和 9 可能是相同的)。
- 每个操作系统都会自行决定如何处理优先级,因为 Java 使用底层操作系统的线程机制。
请务必阅读之后的下一篇文章,其中向您展示了它是如何在 Linux 和 Windows 上完成的。
我认为您的问题可能源于上述第三点(如果您在 Windows 上运行),但也可能是其他任何原因。
关于java - 通过设置优先级来确定线程执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29374755/