可见性的解释应该是保证多个线程对该变量(内存中的某个区域)的“读”是最新。
Declaring a field as volatile differs only in that no locking is involved. In particular, composite read/write operations such as the "++'' operation on volatile variables are not performed atomically.
所以在这种组合读写的场景下,可见性只是不能保证最后的结果,但是它确实在发挥作用。
Using volatile fields can make sense when it is somehow known that only one thread can change a field, but many other threads are allowed to read it at any time.
这也是大神推荐的使用场景。
另外,我们可以反过来考虑,
假设初始x=0,t1和t2均读取到x=0,接下来t1设置x=1之后,
如果t2对x设置值=1,
问1.系统为什么会认为这个操作失效?
问2.失效后怎么处理?
t2在设置x的时候,系统会自动把x=0带上去比较之前x的值?
CAS,除非java把此类的变量都编译成带CAS操作的字节码。
假设也存在以上这一的机制,t2执行x=1失效之后会有什么操作?
抛异常?程序捕获然后又重新读取设置?又回到CAS上面了。
希望对题主有所帮助,如有遗漏欢迎指正。