gpt4 book ai didi

java - 线程不可理解的行为

转载 作者:行者123 更新时间:2023-11-29 06:50:45 25 4
gpt4 key购买 nike

我正在阅读 J. Bloch 的 Effective Java,并发一章中有一个示例:

public class Main {

private static boolean stop;

public static void main(String[] args) throws InterruptedException {

new Thread(() -> {
int i = 0;
while (!stop) {
i++;
}
}).start();

TimeUnit.SECONDS.sleep(1);
stop = true;
}
}

这个例子表明,如果没有同步,子线程将不会停止,因为它看不到主线程所做的更改。但是,如果我们将代码更改为:

public class Main {

private static boolean stop;

public static void main(String[] args) throws InterruptedException {

new Thread(() -> {
while (!stop) {
System.out.println(i);
}
}).start();

TimeUnit.SECONDS.sleep(1);
stop = true;
}
}

应用程序将在 1 秒后停止。那么有人能解释一下为什么 System.out.println 会同步线程,而第一个变体不会吗?

最佳答案

书上解释说这是因为提升编译器优化,第一个代码可能永远运行。

简而言之,代码:

while (!stop)
i++;

可以更改为:

if (!stop)
while (true)
i++;

在第一个示例中,这实际上意味着后台(第二个)线程将永远运行下去;但优化不适用于第二个代码。同步只是作为避免编译器优化的方法之一提出的。有关此优化的更多信息,请访问 this question。和 this one .

关于java - 线程不可理解的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49082256/

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