1
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 是线程安全的吗?

  • 首选的成语是什么,为什么?

4

4 回答 4

5

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

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

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

public class ThreadSafeToo {
    private volatile int aField;
    public void setAField(int value) { aField = value; }
    public int getAField() { return aField; }
}
于 2013-08-02T13:32:07.840 回答
0

Your class DontKnowIfThreadSafeButMostLikelyYes is not thread safe because a static variable is not different from an instance variable from point of synchronization. Besides this the result will not be the same as in the other cases.

Also the second question is opinion based.

于 2013-08-02T13:30:43.100 回答
0

As far as I know DontKnowIfThreadSafeButMostLikelyYes is not thread-safe, because 2 threads could set and get aField at the same moment -> problem

There is no difference if you put the static or not. Both would be not thread-safe.

I think there is no real preferred idom. In this case I would choose the first way. But you can also use the second one or you could use locks.

于 2013-08-02T13:31:17.583 回答
0
Is DontKnowIfThreadSafeButMostLikelyYes thread-safe?

不,因为当同时调用 getter 和 setter 时,getter 可能会返回旧值。

What would be the preferred idiom and why?

在这种情况下,第二类是正确同步的并且是线程安全的

于 2013-08-02T13:31:40.067 回答