# CAS(Compare And Swap) 算法

CAS 也叫自旋锁，用来保证操作的一致性，比如用2个线程同时对一个变量累加1000,000次，得到的结果可能比2000,000少：

``````package juc.test.cas;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;

public class NonAtomicTest {

static long var = 0 ;
@Test
public void testAtomicLong(){

for (int j = 0; j < totalThread; j++) {
@Override
public void run() {
for (int i = 0; i < timesEveryThread; i++) {
var = var + 1;
}
cdl.countDown();
}
}.start();
}

try {
cdl.await();  // wait for all thread return
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(var);
}

}
``````

``````1259956
``````

Java的原子类AtomicInteger等是利用CAS算法实现的，例程的CAS版：

``````package juc.test.cas;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

public class AtomicTest {

@Test
public void testAtomicLong(){
AtomicLong var = new AtomicLong() ;

for (int j = 0; j < totalThread; j++) {
@Override
public void run() {
for (int i = 0; i < timesEveryThread; i++) {
var.getAndIncrement();
}
cdl.countDown();
}
}.start();

}

try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(var.get());
}

}
``````

``````2000000
``````

CAS(Compare And Swap) 算法

(0)
(0)