包子卖完了啊 2016-08-30 05:55 采纳率: 100%
浏览 1137
已采纳

简单的线程优先级的问题

在实现java编程思想的小例子的时候发现运行结果不一样,书上的结果是先执行完优先级最高的才执行优先级低的,但是我的却没有先把优先级最高的线程执行完
代码如下:
package concurrency;

import java.util.concurrent.*;

public class SimplePriorities implements Runnable{

private int countDown = 5;
private int priority;
@SuppressWarnings("unused")
private volatile double d;

public SimplePriorities(int priority) {
    this.priority = priority;
}

public String toString(){
    return Thread.currentThread() + ": " + countDown;
}

@Override
public void run(){ 
    Thread.currentThread().setPriority(priority);
    while(true){
        for(int i = 1; i < 100000; 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-4,1,main]: 5
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-6,10,main]: 3
Thread[pool-1-thread-5,1,main]: 5
Thread[pool-1-thread-6,10,main]: 2
Thread[pool-1-thread-6,10,main]: 1
Thread[pool-1-thread-4,1,main]: 4
Thread[pool-1-thread-1,1,main]: 4
Thread[pool-1-thread-3,1,main]: 4
Thread[pool-1-thread-2,1,main]: 4
Thread[pool-1-thread-5,1,main]: 4
Thread[pool-1-thread-4,1,main]: 3
Thread[pool-1-thread-2,1,main]: 3
Thread[pool-1-thread-1,1,main]: 3
Thread[pool-1-thread-3,1,main]: 3
Thread[pool-1-thread-5,1,main]: 3
Thread[pool-1-thread-3,1,main]: 2
Thread[pool-1-thread-2,1,main]: 2
Thread[pool-1-thread-4,1,main]: 2
Thread[pool-1-thread-1,1,main]: 2
Thread[pool-1-thread-5,1,main]: 2
Thread[pool-1-thread-3,1,main]: 1
Thread[pool-1-thread-4,1,main]: 1
Thread[pool-1-thread-2,1,main]: 1
Thread[pool-1-thread-1,1,main]: 1
Thread[pool-1-thread-5,1,main]: 1
求大神赐教!

  • 写回答

2条回答 默认 最新

  • 当作看不见 2016-08-30 06:33
    关注

    线程优先级高的并不一定会先执行完,优先级的唯一作用就是(两个线程同时)在等待的时候,会优先把资源分配给优先级高的线程(产生优先级高的线程先执行的错觉),如果你的(优先级低)线程已经开始执行了,那么后面优先级高的线程并不会抢夺资源优先执行,而是等待系统分配资源,由于在主函数中是顺序执行的,你把优先级低的线程放在前面(更早开始执行),那它的执行顺序就会在高优先级的前面,优先级一般在高并发中才能体现出来,一两个线程没什么意义

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗