我正在学习 Java 中的多线程,并在下面的代码中测量两个线程 hi 和 lo 的相对 CPU 使用率。
class Clicker implements Runnable{
long 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();
}
}
public class HiLoPri {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Clicker hi = new Clicker(Thread.NORM_PRIORITY +2);
Clicker lo = new Clicker(Thread.NORM_PRIORITY -2);
lo.start();
hi.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
System.out.println("Main Thread interrupted. ");
}
lo.stop();
hi.stop();
try{
hi.t.join();
lo.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted Exception Caught");
}
System.out.println("Low priority : " + lo.click);
System.out.println("High priority : " + hi.click);
}
}
以下是不同优先级的输出:
- lo = NORM_PRIORITY -2 且 hi = NORM_PRIORITY +2: 低优先级:1725664879, 高优先级:1774465713 ||高/低 = 1.02827
- lo = NORM_PRIORITY -4 且 hi = NORM_PRIORITY +4: 低优先级:2142378792, 高优先级:2180156175 ||高/低 = 1.01763
- lo = NORM_PRIORITY 且 hi = NORM_PRIORITY: 低优先级:2582216343, 高优先级:2581415280 ||高/低 = 0.99968
从输出 3 中,我了解到在两个具有相同优先级的线程中,第一个线程的优先级稍高。
对于输出 1 和输出 2,请参阅优先级值。当优先级差异变高时,计数就会增加。但是,当我将差值设置为 0(在输出 3 中)时,与上述观察结果相反,计数显示增加而不是减少。
你能解释一下为什么吗?
(规范:Java SE 7、AMD A10 四核 2.3GHz 和 Window 8)
最佳答案
Java 规范不保证在为线程分配配额时考虑优先级。
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多线程意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437871/