首页 > 解决方案 > 如果 getter 被标记为同步,为什么这段代码会完成?

问题描述

get()尽管字段不是易失性的,为什么当方法被标记为同步时此代码成功完成?如果没有同步,它会在我的机器上无限期地运行(如预期的那样)。

public class MtApp {

    private int value;

    /*synchronized*/ int get() {
        return value;
    }

    void set(int value) {
        this.value = value;
    }

    public static void main(String[] args) throws Exception {
        new MtApp().run();
    }

    private void run() throws Exception {
        Runnable r = () -> {
            while (get() == 0) ;
        };
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(10);
        set(5);
        thread.join();
    }
}

标签: javamultithreadingsynchronizednon-volatile

解决方案


同步力this.value = value发生在之前 get()

它确保更新值的可见性。

没有同步,就没有这样的保证。它可能有效,也可能无效。


推荐阅读