为什么 Java 看不到来自另一个线程的更新值? [英] Why does Java not see the updated value from another thread?

查看:18
本文介绍了为什么 Java 看不到来自另一个线程的更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看这段代码(取自 Effective Java 书籍)

Please look at this code(taken from Effective Java book)

import java.util.concurrent.TimeUnit;


public class Main {
private static boolean stopReq;
public static void main(String[] args) throws InterruptedException {


    Thread bgw = new Thread(new Runnable()
    {
        public void run(){

        int i = 0;
        while(!stopReq){ i++;}
        }
        });
    bgw.start();
    TimeUnit.SECONDS.sleep(1);
    stopReq = true;

}

}

为什么 bgw 线程陷入无限循环?当它到达循环时,它是否缓存了它自己的 stopReq 副本?所以它永远不会看到来自另一个线程的更新值?

Why does the bgw thread get stuck in an infinite loop? Is it caching it's own copy of stopReq when it reached the loop? So it never sees the updated value from the other thread?

我知道解决这个问题的方法是同步或可变变量,但我很好奇为什么当前的实现不起作用.

I understand the solution to this problem would be synchronizing or a volatile variable, but I am curious to why this current implementation doesn't work.

谢谢

推荐答案

你的解释正确.

编译器检测到 stopReq 在循环中从未被修改,并且由于它不是 volatile,所以优化了 while(!stopReq) 指令到 while(true).

The compiler detects than stopReq is never modified in the loop and since it is not volatile, optimizes the while(!stopReq) instruction to while(true).

即使值后来改变,线程甚至不再读取它.

Even though the value changes later, the thread does not even read it any more.

这篇关于为什么 Java 看不到来自另一个线程的更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆