java多线程无效_Java线程优先级无效

这是关于线程优先级的测试.

代码来自Thinking in Java p.809

import java.util.concurrent.*;

public class SimplePriorities implements Runnable {

private int countDown = 5;

private volatile double d; // No optimization

private int priority;

public SimplePriorities(int priority) {

this.priority = priority;

}

public String toString() {

return Thread.currentThread() + ": " + countDown;

}

public void run() {

Thread.currentThread().setPriority(priority);

while (true) {

// An expensive, interruptable operation:

for (int i = 1; i < 10000000; i++) {

d += (Math.PI + Math.E) / (double) i;

if (i % 1000 == 0)

Thread.yield();

}

System.out.println(this);

if (--countDown == 0)

return;

}

}

public static void main(String[] args) {

ExecutorService exec = Executors.newCachedThreadPool();

for (int i = 0; i < 5; i++)

exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));

exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));

exec.shutdown();

}

}

我想知道为什么我不能得到像这样的常规结果:

Thread[pool-1-thread-6,10,main]: 5

Thread[pool-1-thread-6,10,main]: 4

Thread[pool-1-thread-6,10,main]: 3

Thread[pool-1-thread-6,10,main]: 2

Thread[pool-1-thread-6,10,main]: 1

Thread[pool-1-thread-3,1,main]: 5

Thread[pool-1-thread-2,1,main]: 5

Thread[pool-1-thread-1,1,main]: 5

Thread[pool-1-thread-5,1,main]: 5

Thread[pool-1-thread-4,1,main]: 5

...

但随机的结果(每次我运行它改变):

Thread[pool-1-thread-2,1,main]: 5

Thread[pool-1-thread-3,1,main]: 5

Thread[pool-1-thread-4,1,main]: 5

Thread[pool-1-thread-2,1,main]: 4

Thread[pool-1-thread-3,1,main]: 4

Thread[pool-1-thread-1,1,main]: 5

Thread[pool-1-thread-6,10,main]: 5

Thread[pool-1-thread-5,1,main]: 5

...

我使用i3-2350M 2C4T CPU和Win 7 64位JDK 7.

有关系吗 ?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值