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修饰时,程序会报错,截图如下

      

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

      

  • 相关阅读:
    Gated Recurrent Unit (GRU)
    Long Short-Term Memory (LSTM)
    GBDT && XGBOOST
    记录一次网站打开卡--排故障过程
    linux下mysql5.5 5.6 5.7安装教程
    tomcat无法正常shutdown
    linux服务器被入侵的解决方法
    线上CPU 占用300%多-故障解决
    6流程控制-while
    7 流程控制-for序列 for字典
  • 原文地址:https://www.cnblogs.com/cnxieyang/p/12760895.html
Copyright © 2011-2022 走看看