考虑以下代码:
public class World{
public static Point _point;
public static void main(String[] args){
new PointMaker().start();
System.out.println(_point);
}
}
public class Point{
private final int _x, _y;
public Point(int x, int y){
_x = x;
World._point = this;//BAD: publish myself before I'm fully constructed
//some long computation here
_y = y;
}
public void toString(){
return _x + "," + _y;
}
}
public class PointMaker extends Thread{
public void run(){
new Point(1, 1);
}
}
因为Point在设置_y的值之前发布自己,所以对println的调用可能会产生“1,0”而不是预期的“1,1”.
(注意,如果PointMaker Point.它可能也会产生“null”.< init>在执行println调用之前没有足够的设置World._point字段.)