多线程私有构造函数

Ach*_*how 5 java multithreading constructor

在实践中直接从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;
  }
}
Run Code Online (Sandbox Code Playgroud)

以上是一个Thread-safe类:因为它的setter是同步的.我也理解为什么getter不会单独返回x/y而是返回一个数组.我有两个问题.为什么?

  1. private SafePoint(int[] a)
  2. public SafePoint(SafePoint p) { this(p.get()); } 代替 this(p.x,p.y);

ass*_*ias 9

因为调用this(p.x, p.y)不是原子的.换句话说,想象下面的线程交错:

  • 线程1: read p.x
  • 线程2: p.set(otherX, otherY);
  • Thread1:read p.y并调用this(p.x, p.y);

x和y现在来自两个不同的点,可能不一致.

另一方面,p.get()原子地读取x和y(它是synchronized),因此保证了数组中的x和y来自同一点.