【发布时间】:2017-06-30 18:25:02
【问题描述】:
下面的程序应该表明具有较高优先级的线程将占用更多的 CPU 时间。该代码与 Herbert Schildt(印度版)在 The Complete Reference: Java (seventh edition) - Page no 237 & 238 中编写的代码非常相似。
class clicker implements Runnable
{
long click=0;
Thread t;
private volatile boolean running=true;
public clicker(int p)
{
t=new Thread(this,"yo yo");
t.setPriority(p);
}
public void run()
{
while(running)
{click++;}
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
public class ThreadPriorities {
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(Exception e){}
lo.stop();
hi.stop();
try{
hi.t.join();
lo.t.join();
}catch(Exception e){}
System.out.println("Low priority thread : "+lo.click);
System.out.println("High priority thread : "+hi.click);
System.out.println(lo.click<hi.click?true:false);
}
}
一个输出:
低优先级线程:708527884; 高优先级线程:697458303; 假的
另一个输出:
低优先级线程:676775494; 高优先级线程:687116831; 真的
这可能是什么原因?我有一台 4GB RAM 的 Macbook Air。也许这可能是相关的?请告诉我这些不一致输出的原因。提前致谢。
【问题讨论】:
标签: java multithreading thread-priority