java 模拟cas算法

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修改值,保证原子性,并不是所有的修改都能成功
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值