gpt4 book ai didi

具有最高优先级的Java线程不会被执行

转载 作者:行者123 更新时间:2023-12-01 17:57:26 25 4
gpt4 key购买 nike

Main.java:

public class Main {
public static void main(String[] args) {
final Semaphore semp = new Semaphore(1);
for (int facultyNO = 1; facultyNO <= 10; facultyNO++) {
final int NO = facultyNO;
Runnable run = new Runnable() {
public void run() {
try {
while (true) {
semp.acquire();
System.out.println("No." + NO + " grab a candy");
Bowl.candy--;
System.out.println("Candy num left:" + Bowl.candy);
semp.release();
Thread.sleep((long) (1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread faculty = new Thread(run);
faculty.setPriority(Thread.MIN_PRIORITY);
faculty.start();
}
Thread TA = new Thread(() -> {
try {
while (true) {
if (Bowl.candy < 0) {
semp.acquire();
System.out.println("TA fills the candy bowl");
Bowl.candy = 10;
System.out.println("Candy num left:" + Bowl.candy);
semp.release();
}
}
}catch (InterruptedException e) {
e.printStackTrace();
}
});
TA.setPriority(Thread.MAX_PRIORITY);
TA.start();
}
}

碗.java:

public class Bowl {
static int candy = 10;
}

我给线程“TA”最高优先级,因为我希望它在 Bowl.candy=0 填满碗时立即执行。但是,控制台打印:

No.2 grab a candy
Candy num left:9
No.1 grab a candy
Candy num left:8
No.4 grab a candy
Candy num left:7
No.6 grab a candy
Candy num left:6
No.7 grab a candy
Candy num left:5
No.8 grab a candy
Candy num left:4
No.3 grab a candy
Candy num left:3
No.5 grab a candy
Candy num left:2
No.10 grab a candy
Candy num left:1
No.9 grab a candy
Candy num left:0
No.2 grab a candy
Candy num left:-1
No.1 grab a candy
Candy num left:-2
No.4 grab a candy
Candy num left:-3
No.6 grab a candy
Candy num left:-4
No.7 grab a candy
Candy num left:-5
No.8 grab a candy
Candy num left:-6
No.3 grab a candy
Candy num left:-7
No.5 grab a candy
Candy num left:-8
No.10 grab a candy
Candy num left:-9
No.9 grab a candy
Candy num left:-10

看起来像 if (Bowl.candy < 0) 中的代码永远不会被处决。为什么?

最佳答案

在这种情况下,您必须在访问变量之前获取锁:

semp.acquire();
if (Bowl.candy < 0) {
System.out.println("TA fills the candy bowl");
Bowl.candy = 10;
System.out.println("Candy num left:" + Bowl.candy);
}
semp.release();

其他选项:

Bowl.candy 必须声明为 volatile ,否则无法保证其他线程可以看到此变量的更改。或者 Bowl.candy 必须仅在 synchronized block 中访问。

关于具有最高优先级的Java线程不会被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590727/

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