首頁  >  問答  >  主體

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

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++;
    }
}

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

黄舟黄舟2743 天前432

全部回覆(2)我來回復

  • 怪我咯

    怪我咯2017-04-18 10:53:06

    volatile關鍵字就是用來確保記憶體可見度的。

    回覆
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:53:06

    volatile 修飾的value 使用getValue() 讀取的時候,會一直獲取到最新值,滿足可見性
    volatile 能保證一次讀寫可見性,複合操作(比如value++) 不能保證,需要進行加鎖或其他同步措施

    回覆
    0
  • 取消回覆