gpt4 book ai didi

java - 为什么即使我修改了锁变量也会得到一个无限循环?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:03:04 25 4
gpt4 key购买 nike

<分区>

public class GuardedBlock {

private boolean guard = false;

private static void threadMessage(String message) {
System.out.println(Thread.currentThread().getName() + ": " + message);
}

public static void main(String[] args) {
GuardedBlock guardedBlock = new GuardedBlock();

Thread thread1 = new Thread(new Runnable() {

@Override
public void run() {
try {
Thread.sleep(1000);
guardedBlock.guard = true;
threadMessage("Set guard=true");
} catch (InterruptedException e) {
e.printStackTrace();
}

}
});

Thread thread2 = new Thread(new Runnable() {

@Override
public void run() {
threadMessage("Start waiting");
while (!guardedBlock.guard) {
//threadMessage("Still waiting...");
}
threadMessage("Finally!");
}
});

thread1.start();
thread2.start();
}
}

我正在通过 Java 基础教程学习并发。到达 protected 街区并尝试对其进行测试。有一件事我无法理解。

虽然循环是无限的,但是如果你取消注释 threadMessage 行一切正常。为什么?

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