AtomicInteger 類別底層儲存一個int值,並提供方法對該int值進行原子運算。 AtomicInteger 作為java.util.concurrent.atomic
套件的一部分,從Java 1.5開始引入。
1. AtomicInteger基礎用法
透過下文的AtomicInteger
建構方法,可以建立一個AtomicInteger
對象,該物件的初始值預設為0 。 AtomicInteger
提供get和set方法,取得底層int整數值,與設定int整數值
//初始值为0的atomicInteger对象 AtomicInteger atomicInteger = new AtomicInteger(); //初始值为200的atomicInteger对象 AtomicInteger atomicInteger = new AtomicInteger(200); int currentValue = atomicInteger.get(); //100 atomicInteger.set(2453); //现在的值是 2453
但是上面的方法,對於AtomicInteger
來說並不是它的核心內容,AtomicInteger
核心內容體現在它的原子性,我們下文介紹。
2. 什麼時候需要使用AtomicInteger
我們通常在以下的兩個場景下使用AtomicInteger
多執行緒並發場景下操作一個計數器,需要保證計數器操作的原子性。
進行數值比較,如果給定值與目前值相等,則進行數值的更新操作,並實現操作的非阻塞演算法。
2.1. 原子計數器場景
把AtomicInteger
當作一個計數器使用,AtomicInteger
提供了若干方法進行加法、減法的原子運算。
例如從一個map裡面取得值,用get()方法,這是第一個運算;取得到值之後給這個值加上n,這是第二個運算;將進行過加法運算的值,再次放入map裡面是第三個操作。所謂操作的原子性是指:在多執行緒並發的場景下,上面的三個操作是原子性的,也就是不可分割的。不會出現A線程get了數值,B線程同時也get到了該數值,兩個線程同時為該值做運算並先後再次放入的情況,這種情況對於AtomicInteger
而言是不會出現的,AtomicInteger
操作是線程安全的、不可分割的。
addAndGet()
- 將給定的值加到目前值上,並在加法後傳回新值,並保證操作的原子性。
getAndAdd()
- 將給定的值加到目前值上,並傳回舊值,並保證操作的原子性。
incrementAndGet()
- 將目前值增加1,並在增加後傳回新值。它相當於 i
操作,並保證操作的原子性。
getAndIncrement()
- 將目前值增加1並傳回舊值。相當於 i
操作,並保證操作的原子性。
decrementAndGet()
- 將目前值減去1,並在減去後傳回新值,相當於i--
操作,並保證操作的原子性。
getAndDecrement()
- 將目前值減去1,並傳回舊值。它相當於 --i
操作,並保證操作的原子性。
下面是AtomicInteger原子性操作方法的例子
public class Main { public static void main(String[] args) { //初始值为100的atomic Integer AtomicInteger atomicInteger = new AtomicInteger(100); System.out.println(atomicInteger.addAndGet(2)); //加2并返回102 System.out.println(atomicInteger); //102 System.out.println(atomicInteger.getAndAdd(2)); //先获取102,再加2 System.out.println(atomicInteger); //104 System.out.println(atomicInteger.incrementAndGet()); //加1再获取105 System.out.println(atomicInteger); //105 System.out.println(atomicInteger.getAndIncrement()); //先获取105再加1 System.out.println(atomicInteger); //106 System.out.println(atomicInteger.decrementAndGet()); //减1再获取105 System.out.println(atomicInteger); //105 System.out.println(atomicInteger.getAndDecrement()); //先获取105,再减1 System.out.println(atomicInteger); //104 } }
2.2. 數值比對及交換操作
compareAndSet操作將一個記憶體位置的內容與一個給定的值進行比較,只有當它們相同時,才會將該記憶體位置的內容修改為一個給定的新值。這個過程是以單個原子操作的方式完成的。
compareAndSet方法:如果目前值==預期值,則將值設定為給定的更新值。
boolean compareAndSet(int expect, int update)
expect
是預期值
update
是更新值
AtomicInteger compareAndSet() 方法的範例
import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String[] args) { //初始值为100的atomic Integer AtomicInteger atomicInteger = new AtomicInteger(100); //当前值100 = 预期值100,所以设置atomicInteger=110 boolean isSuccess = atomicInteger.compareAndSet(100,110); System.out.println(isSuccess); //输出结果为true表示操作成功 //当前值110 = 预期值100?不相等,所以atomicInteger仍然等于110 isSuccess = atomicInteger.compareAndSet(100,120); System.out.println(isSuccess); //输出结果为false表示操作失败 } }
3. 總結
AtomicInteger
可以幫助我們在不使用synchronized同步鎖定的情況下,實現在多執行緒場景下int數值操作的執行緒安全,操作的原子性。並且使用AtomicInteger
來實現int數值的原子操作,遠比使用synchronized同步鎖定效率更高。
java.util.concurrent.atomic
套件不僅為我們提供了AtomicInteger
,還提供了AtomicBoolean布爾原子操作類、AtomicLong長整型布爾原子操作類、AtomicReference物件原子操作類別、AtomicIntegerArray整數陣列原子操作類別、AtomicLongArray長整型陣列原子操作類別、AtomicReferenceArray物件陣列原子操作類別。
以上是Java並發程式設計:JUC工具包的AtomicInteger原子整型使用範例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具