JAVA AtomicRefence 原子引用CAS

1 AtomicRefence的CAS操作只比较引用变量的引用是否发生变化,若引用没变则设置为新的引用。CAS操作不关心引用的对象的属性变化,只关心引用变化,因为CAS操作用"=="比较原值

CAS思想流程:  now=get()当前值 --> 计算处理 --> CAS比较now? 交换 : 失败(原子完成) 

例如:

public class AtomicRefence测试 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		People name = new People("sw008","1");
		AtomicReference<People> apeople=new AtomicReference<People>(name);
		
		People old=null;
		do {
			System.out.println("do");
			old=apeople.get();
			name.setID("20"); //在此处修改原People(old)
			old.setName("change");//在此处修改原People(old)
			
		} while (!apeople.compareAndSet(old, new People("new", "100"))); //compareAndSet是原子操作
               //CAS依然成功,因为old的引用与apeople的引用对象是一个
		
		System.out.println(apeople.get().getName());
		
	}
	
	

}

class People{
	
	private String name;
	private String ID;
	
	public People(String name, String iD) {
		super();
		this.name = name;
		this.ID = iD;
	}
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getID() {
		return ID;
	}
	public void setID(String iD) {
		ID = iD;
	}
	
	
	
	
}

运行结果:

do
new

 

2 因为cas只能比较一个值/引用,那么要想一次同时比较多个值,就可以使用AtomicRefence,再将多个值封装到一个不可变对象中,其引用交给AtomicRefence。但是一定要注意良好的不可变设计

posted @ 2018-03-17 13:37  sw008  阅读(282)  评论(0编辑  收藏  举报