ITeye博客

CAS

frankytony · 2016-03-09 09:47 · 心得 · 操作系统 · Markdown

CAS 包含三个操作数, 需要读写的内存位置V,进行比较的值A,和拟写入的值B

当且仅当V==A时,CAS 才会用原子操作用B值来更新V的值,否则不执行任何操作,无论V的值是否等于A,

都将返回V 原来的值。

 

 

public class SimulateCAS {

 

private int value;

 

public synchronized int get(){

return value;

}

 

 

public synchronized int compareAndSwap(int expectValue,int newValue){

int oldValue = value;

if(oldValue==expectValue){

oldValue = newValue;

}

return oldValue;

}

 

public synchronized boolean compareAndSet(int expectValue,int newValue){

return expectValue==compareAndSwap(expectValue,newValue);

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。