一. Atomic基本类型
1.基本数据类型
- AtomicInteger
- AtomicLong
- AtomicBoolean
2.常用方法
- int get() // 获取当前值
- int getAndSet(int value) // 获取当前值并设置成指定值等价于普通变量的i = value
- int getAndIncrement() // 自增 ,等价于普通变量的i++
- int getAndDecrement() // 自减,等价于普通变量的i–
- int getAndAdd(int Value) // 加上预期值,等价于普通变量的i = i + value
- boolean compareAndSet(int expect, int update) //如果该对象等于期望值,把它更新成update的值,等价于普通变量的`if (i == expect) {i = update}
二. AtomicInteger
- AtomicInteger 底层采用的是CAS原理(CompareAndSwap)。AtomicInteger 类型的对象,之所以在对AtomicInteger对象操作时,能保证线程安全,是因为在进行操作时,会将当前对象的值与内存中变量的值进行比较,如果是一致的,则进行变量操作,否则继续去内存中获取变量的值,直至当前值,与内存中的值是一致的。
- AtomicInteger 对象,可以通过调用incrementAndGet()方法和getAndIncrement()方法进行值加1的操作,区别在于:incrementAndGet()方法先执行加1操作,然后获取值;getAndIncrement()方法是先获取值然后执行加1的操作;
三. AtomicInteger 对象使用示例:
1.非线程安全的使用示例:
@Slf4j
public class CountExample1 {
public static int clientTotal = 5000;
public static int threadTotal = 200;
public static int count = 0;
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ;</