原子类-AtomicInteger

本文详细介绍AtomicInteger

常用方法介绍

  1.public final int get()  //获取当前的值

  2.public final int getAndSet(int newValue)//获取当前的值并设置新的值

  3.public final int getAndIncrement()//获取当前的值并进行自增操作

  4. public final int getAndDecrement()//获取当前的值并进行自减操作

  5.public final int getAndAdd(int delta)//获取当前的值并加上一个预期的值

  6.boolean compareAndSet(int expect,int update)//如果输入的值等于预期的值,则以原子的方式设置新值,CAS思想的体现。

实例代码

  如下进行getAndIncrement操作,普通变量通过方法加锁实现。见下图代码:

  

package com.yang.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 本实例演示原子类的操作方法,可与非原子类的线程安全问题进行对比;
 * 当我们使用原子类后,可以保证线程安全,是不需要加锁的
 */
public class AtomicIntegerDemo implements Runnable {
    private static final AtomicInteger atomicInteger = new AtomicInteger();

    public void incrementAtomic() {
        atomicInteger.getAndIncrement();
    }

    private static volatile int basicCount = 0;

    /**
     * 此处处理较多时,会影响性能
     */
    public synchronized  void incrementBasic() {
        basicCount++;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            incrementAtomic();
            incrementBasic();
        }
    }

    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("原子类最终结果为:" + atomicInteger.get());
        System.out.println("普通类的最终结果为:" + basicCount);

    }
}

  代码最终的运行结果都是20000

  

猜你喜欢

转载自www.cnblogs.com/cnxieyang/p/12760478.html