• AtomicInteger类简介说明


    转自:

    AtomicInteger类简介说明

    下文笔者讲述AtomicInterger类简介说明,如下所示
    例:

    Integer

    public class Test1 {
        private static Integer count = 0;
    
        synchronized public static void increment() {
            count++;
        }
    }
    

    AtomicInteger

    public class Test2 {
        private static AtomicInteger count = new AtomicInteger(0);
    
        public static void increment() {
            count.getAndIncrement();
        }
    }
    
    从以上代码中,我们可以看出
      使用AtomicInteger修改的变量
       可不使用synchronized修饰,其直接是一个线程安全的变量
    

    AtomicInteger介绍

    AtomicInteger:
       提供原子操作的Integer类
       通过线程安全的方式操作加减
    

    AtomicInteger使用场景

    AtomicInteger 为Integer类型的变量提供原子操作
      常用于高并发场景
    

    AtomicInteger源码

    public class AtomicInteger extends Number implements java.io.Serializable {
        private static final long serialVersionUID = 6214790243416807050L;
    
        // setup to use Unsafe.compareAndSwapInt for updates
        private static final Unsafe unsafe = Unsafe.getUnsafe();
        private static final long valueOffset;
    
        static {
            try {
                valueOffset = unsafe.objectFieldOffset
                    (AtomicInteger.class.getDeclaredField("value"));
            } catch (Exception ex) { throw new Error(ex); }
        }
    
        private volatile int value;
     

    AtomicInteger使用场景

      public class AtomicTest {
    
        static long randomTime() {
            return (long) (Math.random() * 1000);
        }
    
        public static void main(String[] args) {
            // 阻塞队列,能容纳100个文件
            final BlockingQueue queue = new LinkedBlockingQueue(100);
            // 线程池
            final ExecutorService exec = Executors.newFixedThreadPool(5);
            final File root = new File("D:\\Test");
            // 完成标志
            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();
        }
    
    }
    
    AtomicInteger是在使用非阻塞算法实现并发控制
      适用于高并发场景,多线程环境
    
  • 相关阅读:
    瑞萨单片机学习:RA4M3单片机 BOOTloader升级 跳转到主程序 主程序无法执行问题
    ElementUI之CUD+表单验证
    【计算机毕业设计】基于SpringBoot+Vue热门网游推荐网站的设计与实现
    十、Spring Boot 安全管理(4)
    6-5 头插法创建单链表(C) 分数 10
    13-Dubbo服务调用过程源码分析-服务消费方发送请求
    接口自动化测试框架9项必备功能,你知道吗?
    网络安全管理与运维服务
    RENIX_IPv6自动配置——网络测试仪实操
    240503-关于Unity的二三事
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/127419782