Why doesn't volatile in Java update the value of a variable?

后端 未结 3 768
北恋
北恋 2021-01-25 10:36

I\'ve read that "volatile" in Java allows different threads to have access to the same field and see changes the other threads has made to that field. If that\'s the c

3条回答
  •  失恋的感觉
    2021-01-25 11:34

    volatile can make sharing safe (if atomicity of a single read or write operation is sufficient), it doesn't cause sharing.

    Note that if you make d static, it is actually unspecified what value d would have, because the statement d = d + 1 is not atomic, i.e. a thread may be interrupted between reading and writing d. A synchronized block, or an AtomicInteger are the typical solutions for that.

提交回复
热议问题