java 模拟cas算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011877584/article/details/81160541

package com.fjf.juc;

import java.util.Random;

/**
*
* @author fjf
* 模拟cas
* 2018年7月22日 22:34:45
*/
public class TestCAS {

public static void main(String[] args) {
    final Cas cas = new Cas();

for (int i = 0; i < 10; i++) {
    new Thread(new Runnable() {

        @Override
        public void run() {
                int expectValue = cas.getValue();
                //boolean b = cas.CompareAndSwap(expectValue, (int) Math.random()*100);//**注意*100整体的的括号。random()方法,是返回一个[0,1)的浮点数。 (math.random()*100)返回一个[0,100)的浮点数**
                boolean b = cas.CompareAndSwap(expectValue, (int) (Math.random()*100));

                System.out.println(b);
            }
    }).start();
}

}
}
//compare and swap
class Cas{

private int value;

public synchronized int getValue() {
    return value;
}

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

    int oldValue = value;     //先去旧值
    if(expectValue == oldValue){   //旧值与期望的(旧)值 ,一直就修改
        this.value =newValue;
        return  true;
    }else{                         //不一致 就修改失败
        return false;
    }
}

}

//视频中的写法
/*class Cas{
private int value;

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

//比较
public synchronized int compareAndSwap(int expectedValue, int newValue){
    int oldValue = value;

    if(oldValue == expectedValue){
        this.value = newValue;
    }

    return oldValue;
}

//设置
public synchronized boolean compareAndSet(int expectedValue, int newValue){
    return expectedValue == compareAndSwap(expectedValue, newValue);
}

}*/

cas修改值,保证原子性,并不是所有的修改都能成功
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u011877584/article/details/81160541