使用CAS实现的非阻塞计数器

//使用CAS实现的非阻塞计数器
public class CasCount {
	private SimulatedCAS value;
	public int getValue(){
		return value.get();
	}
	public int increment(){
		int v;
		do{
			v = value.get();
		}while(v != value.compareAndSwap(v, v + 1));
		return v + 1;
	}
}
//模拟CAS操作
public class SimulatedCAS {
	private int value;
	public synchronized int get(){
		return value;
	}
	public synchronized int compareAndSwap(int expectedValue,int newValue){
		int oldValue = value;
		if(oldValue == expectedValue){
			value = newValue;
		}
		return oldValue;
	}
	public synchronized boolean compareAndSet(int expectedValue,int newValue){
		return (expectedValue == compareAndSwap(expectedValue, newValue));
	}
}

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class CASTest {
	public static void main(String[] args) {
		Count1 c1 = new Count1();
		for(int i=0; i<2; i++){
			new Thread(c1).start();
		}
	}
}
//Lock-Free算法,不需要加锁,通常都是由三个部分组成
class Count1 implements Runnable{
	private AtomicInteger max = new AtomicInteger();
	public void set(int value){
		while(true){//1、循环
			int current = max.get();
			if(value != current){//满足一定的条件,则进行设置值
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {e.printStackTrace();}
				System.out.println("当前值:"+max.get()+"#"+current);
				if(max.compareAndSet(current, value)){//2、CAS(CompareAndSet)
					break;//3、回退
				}else{
					System.out.println("---------------------------重新比较");
					continue;
				}
			}else{
				break;
			}
		}
	}
	public int getMax(){
		return max.get();
	}
	final Random rand = new Random();
	@Override
	public void run() {
		for(int j=0; j<200; j++){
			int i = rand.nextInt(100+5);
			System.out.println(Thread.currentThread().getName()+"#设置:"+i);
			set(i);
			System.out.println(Thread.currentThread().getName()+"#取得:"+getMax());
		}
	}
}
//使用锁机制来进行同步
class Count2{
	private volatile int max = 0;
	public synchronized void set(int value){
		if(value > max){
			max = value;
		}
	}
	public int getMax(){
		return max;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值