您的位置:首页 > 其它

模拟CAS算法

2020-03-15 18:23 2546 查看

CAS算法

CAS是英文单词CompareAndSwap的缩写,中文意思是:比较并替换。CAS需要有3个操作数:内存地址V,旧的预期值A,即将要更新的目标值B。

CAS指令执行时,当且仅当内存地址V的值与预期值A相等时,将内存地址V的值修改为B,否则就什么都不做。整个比较并替换的操作是一个原子操作。

CAS是乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,
失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。   

在代码中调用原子变量 , 实现cas算法:

import java.util.concurrent.atomic.AtomicInteger;

/**
* @Author liuhaoqi
* @Date 2020/3/9 14:53
* @Version 1.0
*/
public class CAS_diaoyong {
public static void main(String[] args) {
AtomicDemo ad = new AtomicDemo();

//创建10个线程去访问那段代码
for (int i = 0; i <10 ; i++) {
new Thread(ad).start();
}
}

}

class AtomicDemo implements Runnable{

//    private int serialNumber = 0;
private AtomicInteger serialNumber=new AtomicInteger();
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ " :" + getSerialNumber());
}

public int getSerialNumber() {
return serialNumber.getAndIncrement();
}
}

模拟写cas算法,但是和底层代码是不同的,底层代码是硬件实现的。

/**
* @Author liuhaoqi
* @Date 2020/3/9 14:19
* @Version 1.0

CAS是英文单词CompareAndSwap的缩写,中文意思是:比较并替换。CAS需要有3个操作数:内存地址V,旧的预期值A,即将要更新的目标值B。

CAS指令执行时,当且仅当内存地址V的值与预期值A相等时,将内存地址V的值修改为B,否则就什么都不做。整个比较并替换的操作是一个原子操作。

CAS是乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,
失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。   
*/
//模拟cas算法执行
public class CAS_Moni {

public static void main(String[] args) {
final CompareAndSwap cas = new CompareAndSwap();
for (int i = 0; i <10 ; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int expectedValue = cas.get();
boolean b = cas.compareAndSet(expectedValue, (int) (Math.random() * 100));
System.out.println(b+ ": 预估值"+expectedValue);
}
}).start();
}
}

static class CompareAndSwap{
//模拟内存值
private int value;

//获取内存值
public synchronized int get() {
return this.value;
}

//比较并交换
public synchronized int compareAndSwap(int expectedValue,int newValue) {
//获取内存值
int oldValue = value;
//内存值等于预估值 就把value值更新为新的newValue
if (oldValue == expectedValue) {
this.value=newValue;
}
return oldValue;
}

//判断是否修改成功
public synchronized boolean compareAndSet(int expectedValue,int newValue) {
return expectedValue== compareAndSwap(expectedValue,newValue);
}

}

}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
MuNaiTao 发布了13 篇原创文章 · 获赞 0 · 访问量 237 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: