多线程1:AtomicInteger的使用,多线程叠加或叠减
生活随笔
收集整理的這篇文章主要介紹了
多线程1:AtomicInteger的使用,多线程叠加或叠减
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Java語言中,++i和i++操作并不是線程安全的,在使用的時候,不可避免的會用到synchronized關鍵字。而AtomicInteger則通過一種線程安全的加減操作接口
[java]?view plaincopy import?java.util.concurrent.atomic.AtomicInteger;?? ?? public?class?AtomicIntegerTest?{?? ????public?AtomicInteger?inc?=?new?AtomicInteger();?? ?? ????public?void?increase()?{?? ????????inc.getAndIncrement();//i++操作?? ????????//inc.getAndDecrement();//i--操作?? ????}?? ?? ????public?static?void?main(String[]?args)?{?? ????????final?AtomicIntegerTest?test?=?new?AtomicIntegerTest();?? ????????for?(int?i?=?0;?i?<?10;?i++)?{?? ????????????new?Thread()?{?? ????????????????public?void?run()?{?? ????????????????????for?(int?j?=?0;?j?<?1000;?j++)?? ????????????????????????test.increase();?? ????????????????};?? ????????????}.start();?? ????????}?? ?? ????????while?(Thread.activeCount()?>?1)?? ????????????//?保證前面的線程都執行完?? ????????????Thread.yield();?? ????????System.out.println(test.inc);?? ????}?? }??
//?setup?to?use?Unsafe.compareAndSwapInt?for?updates???? private?static?final?Unsafe?unsafe?=?Unsafe.getUnsafe();???? private?static?final?long?valueOffset;???? private?volatile?int?value;????
/**? *?Atomically?increments?by?one?the?current?value.? *? *?@return?the?updated?value? */?? public?final?int?incrementAndGet()?{?? for?(;;)?{?? //這里可以拿到value的最新值?? int?current?=?get();?? int?next?=?current?+?1;?? if?(compareAndSet(current,?next))?? return?next;?? }?? }?? ?? public?final?boolean?compareAndSet(int?expect,?int?update)?{?? //使用unsafe的native方法,實現高效的硬件級別CAS?? return?unsafe.compareAndSwapInt(this,?valueOffset,?expect,?update);?? }??
?好了,看到這個代碼,基本上就看到這個類的核心了。相對來說,其實這個類還是比較簡單的。可以參考http://hittyt.iteye.com/blog/1130990 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
可以發現結果都是10000,也就是說AtomicInteger是線程安全的。
值得一看。
這里,我們來看看AtomicInteger是如何使用非阻塞算法來實現并發控制的。
AtomicInteger的關鍵域只有一下3個:
[java]?view plaincopy
這里, unsafe是Java提供的獲得對對象內存地址訪問的類,注釋已經清楚的寫出了,它的作用就是在更新操作時提供“比較并替換”的作用。實際上就是AtomicInteger中的一個工具。
valueOffset是用來記錄value本身在內存的便宜地址的,這個記錄,也主要是為了在更新操作在內存中找到value的位置,方便比較。
注意:value是用來存儲整數的時間變量,這里被聲明為volatile,就是為了保證在更新操作時,當前線程可以拿到value最新的值(并發環境下,value可能已經被其他線程更新了)。
這里,我們以自增的代碼為例,可以看到這個并發控制的核心算法:
[java]?view plaincopy?好了,看到這個代碼,基本上就看到這個類的核心了。相對來說,其實這個類還是比較簡單的。可以參考http://hittyt.iteye.com/blog/1130990 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的多线程1:AtomicInteger的使用,多线程叠加或叠减的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis传参数
- 下一篇: 一段js面向对象的写法