原子类的概念
java.util.concurrent.atomic
-
不可分割
-
一个操作是不可中断的,即便是多线程的情况下也可以保证
-
原子类的作用与锁类似,是为了保证并发情况下线程安全。
原子类的优势
-
粒度更细
原子变量可以把竞争范围缩小到变量级别,这是我们可以获得的最细粒度的情况,通常锁的粒度都要大于原子变量的粒度
-
效率更高
使用原子类的效率会比使用锁的效率更高,除了高度竞争的情况
六大原子类纵览
Atomic*基本类型原子类
AtomicBoolean
AtomicInteger
AtomicLong
已AtomicInteger为例
常用方法
-
get()
获取当前的值
-
getAndSet(int newValue)
获取当前的值,并设置新的值
-
getAndIncrement()
获取当前的值,并自增
-
getAndDecrement()
获取当前的值,并自减
-
getAndAdd(int delta)
获取当前的值,并加上预期的值
-
compareAndSet(int expect,int update)
如果当前的数值等于预期值,则以原子方式将该值设置为输入值
代码演示
public class AtomicIntegerDemo implements Runnable {
private static final AtomicInteger atomicInt = new AtomicInteger();
private static void getIncrement(){
atomicInt.getAndIncrement();
//atomicInt.getAndDecrement();
//atomicInt.getAndAdd(-1);
//atomicInt.getAndAdd(1);
}
private static volatile int basicCount = 0;
public static void basicCountAdd(){
basicCount++;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
getIncrement();
basicCountAdd();
}
}
public static void main(String[] args) throws InterruptedException {
AtomicIntegerDemo atomicIntegerDemo = new AtomicIntegerDemo();
Thread thread1 = new Thread(atomicIntegerDemo);
Thread thread2 = new Thread(atomicIntegerDemo);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(atomicInt.get()); //20000
System.out.println(basicCount); //19518 (小于等于20000)
}
}
Atomic*Array数组原子类
代码演示
以AtomicIntegerArray为例
public class AtomicArrayDemo {
public static void main(String[] args) throws InterruptedException {
AtomicIntegerArray array = new AtomicIntegerArray(1000);
Decrement decrement = new Decrement(array);
Increment increment = new Increment(array);
Thread[] thread1 = new Thread[100];
Thread[] thread2 = new Thread[100];
for (int i = 0; i < thread1.length; i++) {
thread1[i]</