Java:如何使用synchronized和volatile

Max*_*xii 5 java multithreading volatile synchronized

我有两个主题.第一个线程调用setX方法,第二个线程调用getX方法.我是否必须将方法设置为同步,尽管我只有一个写线程?我可以用第二类和volatile变量解决我的线程问题吗?

public class Test {
    private int x;  

    public synchronized  void setX(int x) {
        this.x = x;
    }

    public synchronized  int getX() {
        return this.x;
    }
}

public class Test2 {
    private volatile int x; 

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return this.x;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

而不是使用synchronized volatile在这里,我个人使用AtomicInteger:

public class Test {
    private final AtomicInteger x = new AtomicInteger();  

    public void setX(int value) {
        x.set(value);
    }

    public int getX() {
        return x.get();
    }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,我已经修复了你的get/ set- 以前你的getX设置,你setX得到了......)

  • @ user1720132:我相信,但不太清楚 - 你需要详细了解Java内存模型才能推理它.使用"AtomicReference",很明显你正在努力实现的目标. (3认同)