本实例代码演示如何讲一个普通对象的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修饰时,程序会报错,截图如下
若变量不可见时,运行截图如下: