我是新来的Java和threads..I的世界,通过一个示例代码正要如下: -理解 “优先级”,在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();
}
}
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);
}
}
但是根据本书的输出结果,具有高优先级的线程应该具有较高的变量答题器值。但在我的情况下,该变量唱首歌值是比更高的优先级one.The输出就像下面我低优先级的线程要高得多: -
hi = 2198713135 lo=2484053552
这是否并不意味着低优先级的线程获得更多的CPU时间比更高的优先级...我缺少的东西..结果是相同的(对较低的优先级线程更高的喀value声值)在Ubuntu和WIN7 ...
2个线程每一个可能有自己的CPU内核,从来就没有将涉及优的争夺。我猜如果你有10个线程,你可能会看到预期的行为。但即使如此,Java线程调度程序比抢先式更合作,所以如果没有明确的'yield()'调用,您可能仍会得到“有趣”的结果。 –
除了上面的内容,对于你的问题的答案是“这不是说较低优先级的线程比较高优先级的线程获得了更多的CPU时间......”是..不。 –
@鹤山那是什么意思? – Rasmus