search

Home  >  Q&A  >  body text

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

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

黄舟黄舟2807 days ago498

reply all(2)I'll reply

  • 怪我咯

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

    volatileThe keyword is used to ensure memory visibility.

    reply
    0
  • 巴扎黑

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

    volatile-modified value will always get the latest value when read using getValue(), which satisfies the visibility.
    volatile can guarantee the visibility of one read and write, but compound operations (such as value++) cannot guarantee it and require locking or other synchronization. Measures

    reply
    0
  • Cancelreply