直接从 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;
}
}
上面是一个线程安全的类:因为它的设置器是同步的。我也理解为什么 getter 不单独返回 x / y 而是返回一个数组。我有 2 个问题。为什么 ?
private SafePoint(int[] a)
public SafePoint(SafePoint p) { this(p.get()); }
代替this(p.x,p.y);