AtomicInteger線程安全使用過程

i++ 線程不安全示例

public class TestAtomicInteger{
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {

        for(int i=0;i<1000;i++){
           new Thread(new Runnable() {
               @Override
               public void run() {
                   for(int j=0;j<100;j++){
                       count++;
                   }
               }
           }).start();
        }
        Thread.sleep(5*1000);
        System.out.println(count);
    }
}

輸出截圖:

result.png


AtomicInteger解決線程安全問題

public class TestAtomicInteger{
    private static AtomicInteger count= new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

        for(int i=0;i<10000;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int j=0;j<1000;j++){
                        count.getAndIncrement();
                    }
                }
            }).start();
        }
        Thread.sleep(5*1000);
        System.out.println(count);
    }
}

輸出截圖:

result.png


思考為什么?

第一種寫法報(bào)錯(cuò),第二種沒有問題

//第一種, idea提示錯(cuò)誤
public class TestAtomicInteger{

    public static void main(String[] args) throws InterruptedException {
        int count = 0;

        for(int i=0;i<1000;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int j=0;j<100;j++){
                        count++;    //錯(cuò)誤提示:Variable 'count' is accessed from within inner class, needs to be final or effectively final
                    }
                }
            }).start();
        }
        Thread.sleep(5*1000);
        System.out.println(count);
    }
}
//第二種, 運(yùn)行結(jié)果正常
public class TestAtomicInteger{

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger count= new AtomicInteger(0);

        for(int i=0;i<10000;i++){
           new Thread(new Runnable() {
               @Override
               public void run() {
                   for(int j=0;j<1000;j++){
                       count.getAndIncrement();
                   }
               }
           }).start();
        }
        Thread.sleep(5*1000);
        System.out.println(count);
    }
}

個(gè)人理解第一種為值傳遞,第二種為引用傳遞;具體不是很清晰,大概感覺是這么個(gè)原因

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

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

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