Java原子操作Atomic
生活随笔
收集整理的這篇文章主要介紹了
Java原子操作Atomic
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載請標明出處:http://blog.csdn.net/zhaoyanjun6/article/details/120854796
本文出自【趙彥軍的博客】
Java線程安全StampedLock
Java線程安全Lock、ReentrantLock、ReentrantReadWriteLock
Java線程安全集合總結
Java原子操作Atomic
文章目錄
- AtomicInteger
- AtomicBoolean
- AtomicLong
- AtomicReference
- AtomicIntegerArray
- AtomicLongArray
Java的java.util.concurrent包除了提供底層鎖、并發集合外,還提供了一組原子操作的封裝類,它們位于java.util.concurrent.atomic包。
AtomicInteger
我們以AtomicInteger為例,它提供的主要操作有:
- 增加值并返回新值:int addAndGet(int delta)
- 加1后返回新值:int incrementAndGet()
- 獲取當前值:int get()
- 用CAS方式設置:int compareAndSet(int expect, int update)
AtomicBoolean
AtomicBoolean atomic = new AtomicBoolean(false); //賦值 atomic.set(true); //取值 atomic.getAndSet(true); atomic.get();AtomicLong
AtomicLong atomic = new AtomicLong(1); //賦值 atomic.set(1); //取值 atomic.getAndIncrement(); atomic.incrementAndGet(); atomic.getAndSet(1); atomic.get();AtomicReference
定義對象
public class User {int id;String name;public User(int id, String name) {this.id = id;this.name = name;} }使用
AtomicReference<User> atomic = new AtomicReference(new User(1, "zhang")); //賦值 atomic.set(new User(2,"zhao")); //取值 atomic.getAndSet(new User(3,"xiao")); atomic.get();AtomicIntegerArray
AtomicIntegerArray atomic = new AtomicIntegerArray(10); //賦值 atomic.set(0,1); //取值 atomic.get(0); atomic.getAndSet(1,100); atomic.getAndIncrement(0); //對下標為0的數據減1 atomic.getAndAdd(0,4); atomic.getAndDecrement(1); //對下標為1的數據減1AtomicLongArray
用法和 AtomicIntegerArray 很像,具體用法略
總結
以上是生活随笔為你收集整理的Java原子操作Atomic的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java线程安全StampedLock
- 下一篇: Java字符串、文件MD5工具类