- 某一个线程的优先级比较低,所以有可能很长时间都没有办法获取cpu的资源,最后被饿死了。
- 从调用start()方法开始进入就绪状态,到最后进入运行状态,需要对cpu的资源进行竞争,而这种竞争是无法完全保证公平的。
- 竞争不到的线程会被饿死,我们只能在一定程度上进行干预
- 导致线程饿死的原因:
a. 高优先级的线程会抢占低优先级线程的时间片。使其无法执行
b. 线程被一直阻塞在等待获取锁的状态,而无可奈何(比如说有两个线程同时去调用一个被synchronized的代码,先获取锁的线程一直在执行而无法结束,那么那个等待中的线程就会出现饥饿问题)
c. 等待的线程永远不被唤醒
5. 如何避免饥饿问题?
5.1 高优先级的线程并不一定比低优先级的线程获取cpu资源块,没有这么绝对。
5.2 不同的系统对优先级的支持是不一样的。
package com.threestone.thread;
public class Target implements Runnable{
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName());
}
}
}
package com.threestone.thread;
/**
-
线程的优先级与饥饿问题
-
@author Administrator
-
启动多个线程并设置不同的优先级
*/
public class ThreadPriority {public static void main(String[] args) {
Thread t1 = new Thread(new Target()); Thread t2 = new Thread(new Target()); t1.setPriority(t1.MAX_PRIORITY); t2.setPriority(t1.MIN_PRIORITY); t1.start(); t2.start();
}
}
从运行结果来看,我们偶尔还是可以看到即使设置了低优先级的线程,也是可以获取到cpu资源的。
- 解决线程被阻塞在了synchronized的同步监视器中导致的饥饿方案:
6.1 使用锁来替代synchronized