3
我不明白为什么t3
不会饿死,因为只有一个锁,并且总是有一些高优先级的线程在等待它(因为我看到它,如果t1
获取锁定,t2
等待,而相反。那么,为什么t3
获得锁?为什么线程没有在我的例子中饿死
public class Starvation {
public static int count = 0;
public static void main(String[] args){
final CountDownLatch latch = new CountDownLatch(3);
final Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
latch.countDown();
latch.await();
while(count<100){
synchronized (lock) {
count++;
System.out.println("Count 1");
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
latch.countDown();
latch.await();
while(count<100){
synchronized (lock) {
count++;
System.out.println("Count 2");
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
try {
latch.countDown();
latch.await();
while(count <100){
synchronized (lock) {
count++;
System.out.println("Count 3");
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我会注意到你有三次_exact same_code - 即使在测试用例中,创建一个'class'和它的三个实例也是一个好习惯。特别是当人们不必手动比较时,请仔细检查您是否正确复制/粘贴了代码... –
您正在使用哪种操作系统?不同的操作系统有不同的线程调度策略 – jalf
鲍里斯蜘蛛 - 你是对的,下次我会的。 jalf-也许我错了,但我不认为它与操作系统有关..因为JVM会安排这个线程。 – user2212726