---
title: "CAS"
author: "frankytony"
date: "2016-03-09T09:47:08Z"
tags: []
categories: ["操作系统"]
slug: "cas"
draft: false
lastmod: "2016-03-09T09:47:08Z"
id: 2281615
url: "https://frankytony.iteye.com/blog/2281615"
---

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);

}

}