zoukankan      html  css  js  c++  java
  • 原子类-AtomicIntegerFieldUpdater

    本实例代码演示如何讲一个普通对象的Int 参数升级包装成原子性。

    注意:该变量是可见的,不能被static修饰。

    实例代码

    package com.yang.atomic;
    
    import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
    
    /**
     * 本实例演示对变量的参数进行升级,让其安全的
     */
    public class AtomicFieldUpdaterDemo implements Runnable {
        static Person personOne = new Person();
        static Person personTwo = new Person();
        AtomicIntegerFieldUpdater<Person> atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
    
        public static void main(String[] args) throws InterruptedException {
            AtomicFieldUpdaterDemo atomicFieldUpdaterDemo = new AtomicFieldUpdaterDemo();
            Thread thread1 = new Thread(atomicFieldUpdaterDemo);
            Thread thread2 = new Thread(atomicFieldUpdaterDemo);
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
            System.out.println("personOne age:"+personOne.age);
            System.out.println("personTwo age:"+personTwo.age);
    
        }
    
    
        @Override
        public void run() {
            //循环1000次
            for (int i = 0; i < 1000; i++) {
                personOne.age++;
                atomicIntegerFieldUpdater.getAndIncrement(personTwo);
            }
        }
    }
    
    class Person {
        volatile int age;
    
    }
    

      运行结果如下图所示:

      

      若采用static修饰时,程序会报错,截图如下

      

       若变量不可见时,运行截图如下:

      

  • 相关阅读:
    硅谷独角兽公司的监控系统长啥样?
    通过jQuery设置全局Ajax加载时呈现Loading
    Jquery遮罩插件,想罩哪就罩哪!
    jquery 读取textarea内容
    easy ui layout 高度 宽度自适应浏览器
    css调节样式
    ORACLE数据库的连接
    spring cloud API网关
    嵌套查询与连接查询的性能
    对于where 1=1 这种条件传入需要'%s'
  • 原文地址:https://www.cnblogs.com/cnxieyang/p/12760895.html
Copyright © 2011-2022 走看看