java - getValue 和 increment 方法是互斥的?

 趣校区导购网 发布于 2022-10-26 10:23
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++;
    }
}

假如一个线程在写,另一个线程在读,不会出现读线程读到的值是写线程还没更新之前的值嘛?也就是读写线程不同步的情况

2 个回答
  • volatile 修饰的 value 使用 getValue() 读取的时候,会一直获取到最新值,满足可见性
    volatile 能保证一次读写可见性,复合操作 (比如 value++) 不能保证,需要进行加锁或其他同步措施

    2022-11-12 01:42 回答
  • volatile关键字就是用来保证内存可见性的。

    2022-11-12 01:42 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有