文章详情页
java - getValue 和 increment 方法是互斥的?
浏览:169日期: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. docker容器呢SSH为什么连不通呢?2. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””3. 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败!4. docker-compose中volumes的问题5. docker gitlab 如何git clone?6. nignx - docker内nginx 80端口被占用7. debian - docker依赖的aufs-tools源码哪里可以找到啊?8. dockerfile - 为什么docker容器启动不了?9. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?10. javascript - 怎么设计项目的返回码,让不同的返回码代表不同的含义?
排行榜

网公网安备