从线程的优先级看饥饿问题

饥饿与公平:

1.高优先级吞噬所有低优先级的CPU时间片

2.线程被永久堵塞在一个等待进入同步块的状态

3.等待的线程永远不被唤醒

 

关于优先级,编程的时候注意:

不要假定高优先级的线程一定先于低优先级的线程,不要有逻辑依赖线程优先级,否则可能有意外错误。因为,不同的平台,对于同一个优先级的数值,可能代表的含义不一样。

但是,大多数我们看到的还是,优先级高的,抢到CPU的概念执行更高。

package com.roocon.thread.t4;

public class Target implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println(Thread.currentThread().getName()+"is running");
        }
    }
}
package com.roocon.thread.t4;

public class Demo {
    public static void main(String[] args) {
        Thread t0 = new Thread(new Target());
        Thread t1 = new Thread(new Target());
        t0.setPriority(Thread.MAX_PRIORITY);
        t1.setPriority(Thread.MIN_PRIORITY);
        t0.start();
        t1.start();
    }
}

运行结果:

Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
Thread-1is running
...//大多数都是Thread-1is running,偶尔是Thread-0is running
Thread-1is running 

 

posted @ 2017-12-07 22:41  凌晨六点半  阅读(287)  评论(0编辑  收藏  举报