理解java线程中的“优先级”

Ras*_*mus 5 java multithreading

我是 java 和线程世界的新手..我刚刚浏览了如下示例代码:-

package com.alice.learnthread;

class NewThread implements Runnable{
Thread t;
long clicker=0;

private volatile boolean running=true;
NewThread(int p){
    t=new Thread(this);
    t.setPriority(p);
}
public void run(){
    while(running){
        clicker++;
    }
}
public void stop(){
    running=false;
}
public void start(){
    t.start();
}
Run Code Online (Sandbox Code Playgroud)

}

 public class TestThread {
public static void main(String[] args){
    Thread r=Thread.currentThread();
    r.setPriority(Thread.MAX_PRIORITY);
    NewThread hi=new NewThread(Thread.NORM_PRIORITY+2);
    NewThread lo=new NewThread(Thread.NORM_PRIORITY-2);
    hi.start();
    lo.start();
    try{
        r.sleep(5000);
    }catch(InterruptedException e){
        System.out.println("caught");
    }
    hi.stop();
    lo.stop();
    try{
        hi.t.join();
        lo.t.join();
    }catch(InterruptedException e){
        System.out.println("cau1");
    }
    System.out.println("hi = "+hi.clicker+" lo="+lo.clicker);
}
Run Code Online (Sandbox Code Playgroud)

}

然而,根据书中的输出,具有高优先级的线程对于变量点击器应该具有更高的价值。但就我而言,较低优先级线程的变量点击器的值比较高优先级线程的值高得多。对我来说,输出如下:-

hi = 2198713135 lo=2484053552
Run Code Online (Sandbox Code Playgroud)

这是否意味着较低优先级的线程比较高优先级的线程获得更多的CPU时间...我是否错过了一些东西..结果在ubuntu和win7上是相同的(较低优先级线程的点击器值较高)...

tib*_*ibo 3

正如 sul 所说,优先级更多的是一种暗示,而不是 JVM 的契约。就您的情况而言,您的结果可以用多种理论来解释:

  • 第二个线程运行得更快,因为它利用了第一个线程的编译优势,并在第一个线程之后停止。
  • 事实上,while 循环检查易失性变量的值,迫使 jvm 实现该值,并在此期间可以为其他线程提供 CPU。
  • stop 方法需要花费大量时间来停止线程。

这只是一些事实,说明线程的行为是不可预测的。例如,尝试首先启动低优先级线程,我相信您会得到不同的结果。

另外,试试这个:

public class TestThread
{
    public static void main(String[] args){
        Thread r=Thread.currentThread();
        r.setPriority(Thread.MAX_PRIORITY);
        NewThread hi=new NewThread(Thread.MAX_PRIORITY);
        NewThread lo=new NewThread(Thread.MIN_PRIORITY);
        hi.start();
        lo.start();
        try{
            r.sleep(5000);
        }catch(InterruptedException e){
            System.out.println("caught");
        }
        hi.interrupt();
        lo.interrupt();

        System.out.println("hi="+hi.clicker);
        System.out.println("lo="+lo.clicker);
    }
}
class NewThread extends Thread{
    long clicker=0;

    NewThread(int p){
        setPriority(p);
    }
    public void run(){
        while(true){
            clicker++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我确信删除 易失性变量并更改线程的停止方式会给您带来其他结果。