1.Atomic下提供了AtomicReferenct类方便来操作对象、数组,如下:
    在并发场景下通过atomicReference来操作同一个user对象类了,从而达到原子性,而不是通过user.age进行直接赋值了。

    1. public class AtomicReferenctSample {
    2. //AtomicReference操作对象
    3. static User user = new User(18);
    4. static AtomicReference<User> atomicReference = new AtomicReference<User>(user);
    5. //AtomicReferenceArray操作数组
    6. static User[] users = new User[]{new User(20),new User(21)};
    7. static AtomicReferenceArray<User> atomicReferenceArray = new AtomicReferenceArray(users);
    8. //AtomicIntegerFieldUpdater修改int
    9. static AtomicIntegerFieldUpdater atomicIntegerFieldUpdaterAge = AtomicIntegerFieldUpdater.newUpdater(User.class,"ageTmp");
    10. //AtomicReferenceFieldUpdater修改String
    11. static AtomicReferenceFieldUpdater atomicReferenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(User.class,String.class,"name");
    12. public static void main(String[] args) {
    13. //并发场景下就可以通过atomicReference来操作同一个user对象类了,从而达到原子性。
    14. System.out.println("----------------AtomicReference---------------");
    15. System.out.println(atomicReference.get().age);
    16. atomicReference.set(new User(19));
    17. System.out.println(atomicReference.get().age);
    18. System.out.println("----------------AtomicReferenceArray---------------");
    19. System.out.println(atomicReferenceArray.get(0).age);
    20. atomicReferenceArray.set(0,new User(22));
    21. System.out.println(atomicReferenceArray.get(0).age);
    22. System.out.println("----------------AtomicIntegerFieldUpdater---------------");
    23. atomicIntegerFieldUpdaterAge.getAndIncrement(user);
    24. System.out.println(atomicIntegerFieldUpdaterAge.get(user));
    25. atomicIntegerFieldUpdaterAge.getAndSet(user,20);
    26. System.out.println(atomicIntegerFieldUpdaterAge.get(user));
    27. System.out.println("----------------AtomicReferenceFieldUpdater---------------");
    28. atomicReferenceFieldUpdater.getAndSet(user,"test");
    29. System.out.println(atomicReferenceFieldUpdater.get(user));
    30. }
    31. static class User{
    32. public User(int age){
    33. this.age = age;
    34. this.ageTmp = age;
    35. }
    36. public int age;
    37. //注意这里如果是想用Atomic原子包下的对应类进行操作的话,要加volatile可见性和public权限
    38. public volatile int ageTmp;
    39. public volatile String name;
    40. }
    41. }