文章详情页
java - getValue 和 increment 方法是互斥的?
浏览:227日期:2024-01-21 08:49:07
问题描述
public class CheesyCounter { // Employs the cheap read-write lock trick // All mutative operations MUST be done with the ’this’ lock held @GuardedBy('this') private volatile int value; public int getValue() { return value; } public synchronized int increment() {return value++; }}
假如一个线程在写,另一个线程在读,不会出现读线程读到的值是写线程还没更新之前的值嘛?也就是读写线程不同步的情况
问题解答
回答1:volatile关键字就是用来保证内存可见性的。
回答2:volatile 修饰的 value 使用 getValue() 读取的时候,会一直获取到最新值,满足可见性volatile 能保证一次读写可见性,复合操作 (比如 value++) 不能保证,需要进行加锁或其他同步措施


标签:
java
相关文章:
1. html5 - iframe src可以引入其他域名或者IP吧iframe src可以是其他域名过IP吧2. javascript - 给js写的盒子添加css样式,css样式没起作用。3. javascript - 如何将psd裁切下来的图片非常清晰的宣示出来4. javascript - vuex中action应该怎么分发事件5. html5 - 请问一下写H5的时候 你们都是兼容那些手机6. html5 - ElementUI table中el-table-column怎么设置百分比显示。7. mysqli函数8. web前端页面中实现表格效果,这个表格是可编辑的9. javascript - h5页面中iframe无法唤起iOS应用?10. 数据挖掘 - 如何用python实现《多社交网络的影响力最大化问题分析》中的算法?
排行榜
![php-_server-php_self - nginx $_SERVER[’PHP_SELF’] 得到重复路径是什么原因?](http://www.haobala.com/attached/image/news/202309/1123091c0c.png)
网公网安备