public class ThreadSafe {

    private int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public synchronized int getAField() {
        return aField;
    }

}

public class ThreadSafeToo {

    private volatile int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public int getAField() {
        return aField;
    }

}

public class DontKnowIfThreadSafeButMostLikelyYes {

    private static int aField;

    public synchronized void setAField(int value) {
        aField = value;
    }

    public int getAField() {
        return aField;
    }

}


问题:


DontKnowIfThreadSafeButMostLikelyYes是线程安全的吗?
首选的惯用法是什么,为什么?

最佳答案

ThreadSafeToo不需要同步方法:volatile分配是原子的,并提供可见性保证。

DontKnowIfThreadSafeButMostLikelyYes不是线程安全的:您需要同步读取和写入共享变量。

首选惯用语是主观的,但是在您的情况下,有效的方法是:

public class ThreadSafeToo {
    private volatile int aField;
    public void setAField(int value) { aField = value; }
    public int getAField() { return aField; }
}

08-05 10:01