私は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);
}
}
ただし、本の出力によると、優先度の高いスレッドは変数クリッカーの値が高くなるはずです。しかし、私の場合、変数クリッカーの値は、優先度の高いスレッドよりも優先度の低いスレッドの方がはるかに高くなります。出力は次のようになります。
hi = 2198713135 lo=2484053552
これは、優先度の低いスレッドが優先度の高いスレッドよりも多くの CPU 時間を取得したという意味ではありません...何か不足していますか..ubuntu と win7 の両方で結果は同じです (優先度の低いスレッドのクリッカー値が高い)...