CAS是compare and swap的縮寫,即我們所說的比較交換。cas是一種基於鎖的操作,而且是樂觀鎖。
在java中鎖分為樂觀鎖和悲觀鎖
synchronized就是一種悲觀鎖(獨占鎖),會導致其它所有需要鎖的線程掛起,等待持有鎖的線程釋放鎖。
而樂觀鎖采取了一種寬泛的態度,通過某種方式不加鎖來處理資源,比如通過給記錄加version來獲取數據,性能較悲觀鎖有很大的提高
//代碼轉自 https://blog.csdn.net/u011381576/article/details/79922538
@Test
public void testCas() throws InterruptedException {
for (int i = 1; i <= 3; i++) {
MyThrend thrend = new MyThrend("thead" + i);
Thread thread = new Thread(thrend);
thread.start();
}
Thread.sleep(2000);
System.out.println(MyCount.count.get());
}
static class MyThrend implements Runnable {
private String name;
MyThrend(String threadName) {
this.name = threadName;
}
@Override
public void run() {
for (int i=0;i<20;i++){
MyCount.count.getAndIncrement(); //加1方法
System.out.println(name+"*"+MyCount.count.get());
}
}
}
private static class MyCount {
static AtomicInteger count = new AtomicInteger(0);
}
//java.util.current.atomic包下面,采用了CAS機制來實現加鎖