更新時間:2022-08-04 09:59:02 來源:動力節(jié)點 瀏覽1297次
CAS是compare and swap的縮寫,即我們所說的比較交換。cas是一種基于鎖的操作,而且是樂觀鎖。在線程鎖分類中,鎖分為樂觀鎖和悲觀鎖。悲觀鎖是將資源鎖住,等一個之前獲得鎖的線程釋放鎖之后,下一個線程才可以訪問。而樂觀鎖采取了一種寬泛的態(tài)度,通過某種方式不加鎖來處理資源,比如通過給記錄加version來獲取數(shù)據(jù),性能較悲觀鎖有很大的提高。
CAS 操作包含三個操作數(shù) —— 內(nèi)存位置(V)、預(yù)期原值(A)和新值(B)。如果內(nèi)存地址里面的值和A的值是一樣的,那么就將內(nèi)存里面的值更新成B。CAS是通過無限循環(huán)來獲取數(shù)據(jù)的,若果在第一輪循環(huán)中,a線程獲取地址里面的值被b線程修改了,那么a線程需要自旋,到下次循環(huán)才有可能機(jī)會執(zhí)行。
(1)CAS容易造成ABA問題。一個線程a將數(shù)值改成了b,接著又改成了a,此時CAS認(rèn)為是沒有變化,其實是已經(jīng)變化過了,而這個問題的解決方案可以使用版本號標(biāo)識,每操作一次version加1。在java5中,已經(jīng)提供了AtomicStampedReference來解決問題。
(2)CAS造成CPU利用率增加。之前說過了CAS里面是一個循環(huán)判斷的過程,如果線程一直沒有獲取到狀態(tài),cpu資源會一直被占用。
其實AutoInteger就是使用了CAS來實現(xiàn)加1,我們知道如果有一個共享變量count=1,開5個線程,每個線程加20次,結(jié)果一般來說都會小于100.
@Test
public void test20() throws InterruptedException {
for (int i = 1; i <= 5; i++) {
MyThrend thrend = new MyThrend("thead" + i);
Thread thread = new Thread(thrend);
thread.start();
}
Thread.sleep(2000);
System.out.println(MyCount1.count);
}
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++)
MyCount1.count++;
}
}
private static class MyCount1 {
static int count = 0;
}
結(jié)果78
現(xiàn)在修改一個代碼,將int變成AtomicInteger
@Test
public void test20() throws InterruptedException {
for (int i = 1; i <= 5; 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方法
}
}
private static class MyCount {
static AtomicInteger count = new AtomicInteger(0);
}
每次結(jié)果都是100,怎么做到的呢?這里是沒有直接加鎖的,看源碼。
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1); //第一個參數(shù)當(dāng)前對象地址,第二個參數(shù)數(shù)據(jù)偏移量,第三個參數(shù)每次指定默認(rèn)加1
}
public final int getAndAddInt(Object var1, long var2, int var4) { //這個方法使用的就是CAS,核心在于循環(huán)比較內(nèi)存里面的值和當(dāng)前值是否相等,如果相等就用新值覆蓋
int var5;
do {
var5 = this.getIntVolatile(var1, var2); //如果a,b線程同時執(zhí)行這個方法,a線程拿到值1后cpu執(zhí)行時間到了掛起,b開始執(zhí)行,也拿到1,但是沒有掛起,接著將值變成了2
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4)); //這個時候a線程恢復(fù)執(zhí)行,去比較的時候發(fā)現(xiàn)手上的1 和內(nèi)存里面的值2不等,這個時候他要進(jìn)行下一個循環(huán),看出來了占用cpu吧
return var5;
}
AtomicInteger,AtomicLong,AtomicBoolean.....都在java.util.current.atomic包下面,采用了CAS機(jī)制來實現(xiàn)加鎖。如果大家想了解更多相關(guān)知識,可以關(guān)注動力節(jié)點的多線程教程中的部分內(nèi)容,這是掌握多線程線程鎖種類的必學(xué)內(nèi)容,為我們后面學(xué)習(xí)多線程的更多內(nèi)容打下堅實的基礎(chǔ)。
初級 202925
初級 203221
初級 202629
初級 203743