gpt4 book ai didi

java - 为什么线程在我的例子中没有被饿死

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:52 24 4
gpt4 key购买 nike

我不明白为什么 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();
}
}
}

最佳答案

I cant understand why t3 isn't getting starved, since there is only one lock and there is always some high priority thread waiting on it (as i see it, if t1 acquire the lock, t2 waits, and the opposite.. so why t3 do get the lock?

典型线程实现的优先级特别会尽量不让线程饿死。如果有优先级更高的线程,那么它们可能会运行 更多 t3t3 将被赋予周期。此外,如果您的硬件有超过 2 个 CPU,则 t3 可能会被安排在 hibernate CPU 上,而不管其他线程的优先级如何。

例如,我见过保持优先级和优先级计数器的线程优先级系统。每次线程获得时间片时,其优先级计数器都会递减。然后当它达到 0 时,它会再次回到最大值。这意味着在某个时候,较低优先级的线程将具有相同或更高的优先级计数器,并将获得周期。但这是特定于操作系统的,可能还有其他方法可以实现。

实际上,线程的优先级应该被视为对底层操作系统的提示。尽管我编写了很多线程代码,但我很少使用优先级。

关于java - 为什么线程在我的例子中没有被饿死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20706959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com