CAS算法

一、i++ 的原子性問題:int i=i++ 的操作實際上分為三個步驟“讀-改-寫”

第一步:int temp = i;
第二步:i = i + 1;
第三步:i = temp;

二、原子變量:在 java.util.concurrent.atomic 包下提供了一些原子變量。
  1. volatile 保證內(nèi)存可見性
  2. CAS(Compare-And-Swap) 算法保證數(shù)據(jù)變量的原子性。CAS 算法是硬件對于并發(fā)操作的支持,CAS 包含了三個操作數(shù):
  • 內(nèi)存值 V
  • 預(yù)估值 A
  • 更新值 B
當(dāng)且僅當(dāng) V == A 時, V = B; 否則,不會執(zhí)行任何操作。

A、多線程操作,保證內(nèi)存變量原子性的示例代碼

import java.util.concurrent.atomic.AtomicInteger;

public class TestAtomicDemo {

    public static void main(String[] args) {
//      int  i = 1;
//      i = i++;
//      System.out.println(i);  
//              輸出1
        
        AtomicDemo ad = new AtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(ad).start();
        }
    }
    
}

class AtomicDemo implements Runnable{
    
    //  當(dāng)多線程操作時,volatile關(guān)鍵字無法保證原子性
    //  private volatile int serialNumber = 0;
    
    private AtomicInteger serialNumber = new AtomicInteger(0);

    @Override
    public void run() {
        
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        
        System.out.println(getSerialNumber());
    }
    
    public int getSerialNumber(){
//      return serialNumber++;
        
        return serialNumber.getAndIncrement();
    }
    
}

B、模擬 CAS 算法的示例代碼

public class TestCompareAndSwap {

    public static void main(String[] args) {
        final CompareAndSwap cas = new CompareAndSwap();
        
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    
                    int expectedValue = cas.get();
                    boolean b = cas.compareAndSet(expectedValue, (int)(Math.random() * 101));
                    System.out.println(b);
                    
                }
            }).start();
        }
        
    }
    
}

class CompareAndSwap{
    private int value;
    
    //獲取內(nèi)存值
    public synchronized int get(){
        return value;
    }
    
    //比較
    public synchronized int compareAndSwap(int expectedValue, int newValue){
        int oldValue = value;
        
        if(oldValue == expectedValue){
            this.value = newValue;
        }
        
        return oldValue;
    }
    
    //設(shè)置
    public synchronized boolean compareAndSet(int expectedValue, int newValue){
        return expectedValue == compareAndSwap(expectedValue, newValue);
    }
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區(qū)別 13、...
    Miley_MOJIE閱讀 3,894評論 0 11
  • 一、線程 1.1 線程的概述 一個運行程序就是一個進(jìn)程,而線程是進(jìn)程中獨立運行的子任務(wù) 線程是操作系統(tǒng)執(zhí)行流中的最...
    itcjj閱讀 1,050評論 0 8
  • 簡書 賈小強(qiáng)轉(zhuǎn)載請注明原創(chuàng)出處,謝謝! 一個Java 5中最好的補(bǔ)充是對原子操作的支持類,如AtomicInteg...
    賈小強(qiáng)閱讀 623評論 0 2
  • 《UNIX 網(wǎng)絡(luò)編程卷一:套接字聯(lián)網(wǎng)API》筆記 套接字 套接字編程接口,是在 TCP/IP 協(xié)議族中,應(yīng)用層進(jìn)入...
    超net閱讀 5,983評論 2 13
  • 第二遍看《圣誕玫瑰》,心情很復(fù)雜。 楊采妮作為明星,我?guī)缀鯖]有記住她任何作品,作為導(dǎo)演,2013年她的處女作《圣誕...
    斷翅蝴蝶閱讀 991評論 0 4

友情鏈接更多精彩內(nèi)容