关闭

AtomicRefrence 和 枚举

424人阅读 评论(0) 收藏 举报
分类:
public abstract class AbstractFoo {
	private int x,y; 
	private enum State{NEW,INITIALIZING,INITIALIZED} 
	private final AtomicReference<State> init = new AtomicReference<State>(State.NEW); 
	public AbstractFoo(int x,int y){initialize(x,y);} 
	protected AbstractFoo(){}; 
	protected final void initialize(int  x ,int y){
		if(!init.compareAndSet(State.NEW, State.INITIALIZING)){
			throw new IllegalStateException("Already initialized");
		}
		this.x = x;
		this.y =y;
		init.set(State.INITIALIZED);
	} 
	protected int getX(){checkInit();return x;}
	protected int getY(){checkInit();return y;} 
	private void checkInit(){
		if(init.get()!=State.INITIALIZED){
			throw new IllegalStateException("Not initialized");
		}
	} 
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42010次
    • 积分:636
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:121篇
    • 译文:0篇
    • 评论:0条