5

実際のJava並行性からまっすぐ:

@ThreadSafe
public class SafePoint {
  @GuardedBy("this") private int x, y;
  private SafePoint(int[] a) { this(a[0], a[1]); }
  public SafePoint(SafePoint p) { this(p.get()); }
  public SafePoint(int x, int y) {
     this.x = x;
     this.y = y;
   }
  public synchronized int[] get() {
     return new int[] { x, y };
  }
  public synchronized void set(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

上記はスレッドセーフなクラスです。セッターが同期されているためです。ゲッターが x / y を個別に返さず、代わりに配列を返す理由も理解しています。2 つの質問があります。なんで ?

  1. private SafePoint(int[] a)
  2. public SafePoint(SafePoint p) { this(p.get()); }それ以外のthis(p.x,p.y);
4

1 に答える 1

9

呼び出しthis(p.x, p.y)はアトミックではないためです。つまり、次のスレッド インターリーブを想像してください。

  • スレッド 1:read p.x
  • スレッド 2:p.set(otherX, otherY);
  • スレッド 1:read p.yおよび呼び出しthis(p.x, p.y);

x と y は 2 つの異なるポイントからのものであり、一貫性がない可能性があります。

一方、 はp.get()x と y をアトミックに読み取る (synchronizedつまり ) ため、配列内の x と y が同じポイントからのものであることが保証されます。

于 2012-12-20T10:27:52.450 に答える