转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/120854796
本文出自【赵彦军的博客】
Java线程安全StampedLock
Java线程安全Lock、ReentrantLock、ReentrantReadWriteLock
Java线程安全集合总结
Java原子操作Atomic
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的数据减1
AtomicLongArray
用法和 AtomicIntegerArray 很像,具体用法略