原子类AtomicInteger

介绍

AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。

实现原理

AtomicInteger简单来说就是一个能进行原子操作的Integer,这样在多线程操作下对AtomicInteger的操作是原子操作的,操作后的值对所有线程都是立即可见的。

简单来说其实现就是使用的volatile变量 value和sun.misc.Unsafe提供的CAS操作完成的,volatile变量value就表明任意一个线程对value的操作都是对其他线程可见的,并且对于value的修改使用Unsafe提供的方法实现线程不阻塞来完成对value值的修改等操作。

AtomicInteger的变量值:

private volatile int value;

get和set操作就是直接赋值给value

 /**
     * Gets the current value.
     * @return the current value
     */
    public final int get() {
        return value;
    }

    /**
     * Sets to the given value.
     * @param newValue the new value
     */
    public final void set(int newValue) {
        value = newValue;
    }

加加和减减操作就是使用Unsafe提供的方法完成CAS操作

/**
  * Atomically increments by one the current value.
  * @return the updated value
  */
 public final int incrementAndGet() {
     return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
 }

 /**
  * Atomically decrements by one the current value.
  * @return the updated value
  */
 public final int decrementAndGet() {
     return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
 }

实例使用

以下就是在多线程情况下,使用AtomicInteger的一个实例,这段代码是借用IT宅中的一段代码。

public class AtomicMain {
    static long randomTime() {
        return (long) (Math.random() * 1000);
    }

    public static void main(String[] args) {
        // 阻塞队列,能容纳100个文件
        final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
        // 线程池
        final ExecutorService exec = Executors.newFixedThreadPool(5);
        final File root = new File("D:\\MySoftware");
        // 完成标志
        final File exitFile = new File("");
        // 原子整型,读个数
        // AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
        final AtomicInteger rc = new AtomicInteger();
        // 原子整型,写个数
        final AtomicInteger wc = new AtomicInteger();
        // 读线程
        Runnable read = new Runnable() {
            public void run() {
                scanFile(root);
                scanFile(exitFile);
            }

            public void scanFile(File file) {
                if (file.isDirectory()) {
                    File[] files = file.listFiles(new FileFilter() {
                        public boolean accept(File pathname) {
                            return pathname.isDirectory() || pathname.getPath().endsWith(".iso");
                        }
                    });
                    for (File one : files)
                        scanFile(one);
                } else {
                    try {
                        // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
                        int index = rc.incrementAndGet();
                        System.out.println("Read0: " + index + " " + file.getPath());
                        // 添加到阻塞队列中
                        queue.put(file);
                    } catch (InterruptedException e) {

                    }
                }
            }
        };
        // submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
        exec.submit(read);

        // 四个写线程
        for (int index = 0; index < 4; index++) {
            // write thread
            final int num = index;
            Runnable write = new Runnable() {
                String threadName = "Write" + num;

                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(randomTime());
                            // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
                            int index = wc.incrementAndGet();
                            // 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
                            File file = queue.take();
                            // 队列已经无对象
                            if (file == exitFile) {
                                // 再次添加"标志",以让其他线程正常退出
                                queue.put(exitFile);
                                break;
                            }
                            System.out.println(threadName + ": " + index + " " + file.getPath());
                        } catch (InterruptedException e) {
                        }
                    }
                }

            };
            exec.submit(write);
        }
        exec.shutdown();
    }
}

执行以上代码结果如下:

Read0: 1 D:\MySoftware\VMware12\freebsd.iso
Write1: 1 D:\MySoftware\VMware12\freebsd.iso
Read0: 2 D:\MySoftware\VMware12\linux.iso
Write3: 2 D:\MySoftware\VMware12\linux.iso
Read0: 3 D:\MySoftware\VMware12\netware.iso
Write2: 3 D:\MySoftware\VMware12\netware.iso
Read0: 4 D:\MySoftware\VMware12\solaris.iso
Write0: 4 D:\MySoftware\VMware12\solaris.iso
Read0: 5 D:\MySoftware\VMware12\windows.iso
Read0: 6 D:\MySoftware\VMware12\winPre2k.iso
Write1: 5 D:\MySoftware\VMware12\windows.iso
Read0: 7 
Write1: 6 D:\MySoftware\VMware12\winPre2k.iso

使用场景

AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用。

总结

简单来说AtomicInteger的实现原理就是通过一个volatile的变量value以及Unsafe类提供的CAS操作来完成的。
AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。


参考文档:
1. https://blog.csdn.net/qq924862077/article/details/68943417

猜你喜欢

转载自blog.csdn.net/thebigdipperbdx/article/details/80056247