gpt4 book ai didi

Java多线程意外结果

转载 作者:行者123 更新时间:2023-12-01 12:48:36 27 4
gpt4 key购买 nike

我正在学习 Java 中的多线程,并在下面的代码中测量两个线程 hilo 的相对 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);
}

}

以下是不同优先级的输出:

  1. lo = NORM_PRIORITY -2 且 hi = NORM_PRIORITY +2:低优先级:1725664879,高优先级:1774465713 ||高/低 = 1.02827
  2. lo = NORM_PRIORITY -4 且 hi = NORM_PRIORITY +4:低优先级:2142378792,高优先级:2180156175 ||高/低 = 1.01763
  3. 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com