V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wangyu17455
V2EX  ›  Java

关于 volatile

  •  
  •   wangyu17455 ·
    yu1745 · 2022-12-03 20:59:34 +08:00 · 893 次点击
    这是一个创建于 481 天前的主题,其中的信息可能已经有所发展或是发生改变。

    不知道为什么有这么多人在测试 volatile 的作用的时候喜欢用 println 这个方法,然后因为 println 方法的特殊性就得出一个结论,volatile 其实加和不加都一样。 首先,println 内部有 synchronized ,它的特殊性指的就是这一点。这会导致缓存失效,进而导致变量的重新读取,无论加没加 volatile 。

    while(aBoolean){
    	System.out.println("running");
    }
    

    上面这种方式检验 volatile 是绝对错误的! 正确的方式是

    while(aBoolean){}
    System.out.println("done");
    

    这将导致线程永远空转,而加了 volatile 之后就可以正确的输出 done

    L4Linux
        1
    L4Linux  
       2022-12-04 01:25:15 +08:00 via Android
    println 的 synchronized 只保证输出的原子性吧,管得着方法外的变量吗?你不妨举例说说其它 threads 有怎样的代码。
    wangyu17455
        2
    wangyu17455  
    OP
       2022-12-04 02:12:01 +08:00
    @L4Linux
    Concurrent Programming in Java 里说了啊
    In essence, releasing a lock forces a flush of all writes from working memory employed by the thread, and acquiring a lock forces a (re)load of the values of accessible fields. While lock actions provide exclusion only for the operations performed within a synchronized method or block, these memory effects are defined to cover all fields used by the thread performing the action.
    是当前作用域的所有变量都 reload from memory
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   964 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:23 · PVG 04:23 · LAX 13:23 · JFK 16:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.