我正在尝试测试2个线程,一个线程具有较高的优先级,而另一个线程具有较低的优先级.
根据我的结果,有时低优先级线程速度更快,这怎么可能?
我已经通过增加每个线程内的click变量来测试了不同优先级的线程.
我也增加和减少了睡眠时间,但是什么也没有.
由于我是在后台不运行繁重程序的情况下进行测试的,因此我决定在运行高清影片的情况下进行测试,但仍然没有真正的变化,线程的速度始终相同.
我的电脑是Intel i5.我正在运行Windows 7 64位,16GB RAM
这是代码:
class clicker implements Runnable{
long click =0;
Thread t;
private volatile boolean running = true;
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();
}
}
class HiLoPri {
public static void main(String args[]){
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi=new clicker(Thread.NORM_PRIORITY+4);
clicker lo=new clicker(Thread.NORM_PRIORITY-4);
lo.start();
hi.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
lo.stop();
hi.stop();
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("LO: "+lo.click);
System.out.println("HI: "+hi.click);
}
}
最佳答案
你有两个问题.一个是线程需要一段时间才能启动,因此您可以通过顺序触发它们来给“低”一个不错的开始.另一个是线程优先级决定了在有处理器时间参数的情况下谁可以运行.有两个线程和8个有效的处理器内核,优先级并没有多大关系!这是一个固定的示例,该示例使用闩锁“同时”启动所有线程,并使用足够的线程实际争夺资源,您可以看到优先级设置的效果.它给出了相当一致的结果.
static class Clicker implements Runnable{
BigInteger click = BigInteger.ZERO;
Thread t;
Clicker(int p){
t=new Thread(this);
t.setPriority(p);
}
public void run(){
try {
latch.await();
} catch(InterruptedException ie) {}
while(running)
click = click.add(BigInteger.ONE);
}
public void start(){
t.start();
}
}
public static volatile boolean running = true;
public static final CountDownLatch latch = new CountDownLatch(1);
public static void main(String args[]){
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
List listLow = new ArrayList();
List listHigh = new ArrayList();
for (int i = 0; i < 16; i++) {
listHigh.add(new Clicker(Thread.NORM_PRIORITY+4));
}
for (int i = 0; i < 16; i++) {
listLow.add(new Clicker(Thread.NORM_PRIORITY-4));
}
for (Clicker clicker: listLow) {
clicker.start();
}
for (Clicker clicker: listHigh) {
clicker.start();
}
latch.countDown();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
running = false;
BigInteger lowTotal = BigInteger.ZERO;
BigInteger highTotal = BigInteger.ZERO;
try {
for (Clicker clicker: listLow) {
clicker.t.join();
lowTotal = lowTotal.add(clicker.click);
}
for (Clicker clicker: listHigh) {
clicker.t.join();
highTotal = highTotal.add(clicker.click);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("LO: "+lowTotal);
System.out.println("HI: "+highTotal);
}
这篇博客探讨了线程优先级对执行速度的影响。作者在测试中发现,即使设置了不同的优先级,线程的速度表现仍然相似。文章解释了线程启动延迟和处理器资源分配对优先级影响的关系,并提供了一个示例代码,展示了如何通过控制线程启动和资源竞争来观察优先级效果。实验结果显示,在多线程和多核心处理器环境下,优先级的影响可能并不显著。
439

被折叠的 条评论
为什么被折叠?



