>  Q&A  >  본문

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일 전430

모든 응답(2)나는 대답할 것이다

  • 怪我咯

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

    volatile 키워드는 메모리 가시성을 보장하는 데 사용됩니다.

    회신하다
    0
  • 巴扎黑

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

    휘발성으로 수정된 값을 getValue()를 사용하여 읽으면 항상 최신 값을 가져오므로 가시성을 충족합니다.
    Volatile은 한 번의 읽기 및 쓰기의 가시성을 보장할 수 있지만 복합 연산(예: value++) )는 이를 보장할 수 없으며 잠금 또는 기타 동기화 조치를 추가해야 합니다

    회신하다
    0
  • 취소회신하다