//使用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;
}
}
//使用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.c