1.Atomic下提供了AtomicReferenct类方便来操作对象、数组,如下:
在并发场景下通过atomicReference来操作同一个user对象类了,从而达到原子性,而不是通过user.age进行直接赋值了。
public class AtomicReferenctSample {
//AtomicReference操作对象
static User user = new User(18);
static AtomicReference<User> atomicReference = new AtomicReference<User>(user);
//AtomicReferenceArray操作数组
static User[] users = new User[]{new User(20),new User(21)};
static AtomicReferenceArray<User> atomicReferenceArray = new AtomicReferenceArray(users);
//AtomicIntegerFieldUpdater修改int
static AtomicIntegerFieldUpdater atomicIntegerFieldUpdaterAge = AtomicIntegerFieldUpdater.newUpdater(User.class,"ageTmp");
//AtomicReferenceFieldUpdater修改String
static AtomicReferenceFieldUpdater atomicReferenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(User.class,String.class,"name");
public static void main(String[] args) {
//并发场景下就可以通过atomicReference来操作同一个user对象类了,从而达到原子性。
System.out.println("----------------AtomicReference---------------");
System.out.println(atomicReference.get().age);
atomicReference.set(new User(19));
System.out.println(atomicReference.get().age);
System.out.println("----------------AtomicReferenceArray---------------");
System.out.println(atomicReferenceArray.get(0).age);
atomicReferenceArray.set(0,new User(22));
System.out.println(atomicReferenceArray.get(0).age);
System.out.println("----------------AtomicIntegerFieldUpdater---------------");
atomicIntegerFieldUpdaterAge.getAndIncrement(user);
System.out.println(atomicIntegerFieldUpdaterAge.get(user));
atomicIntegerFieldUpdaterAge.getAndSet(user,20);
System.out.println(atomicIntegerFieldUpdaterAge.get(user));
System.out.println("----------------AtomicReferenceFieldUpdater---------------");
atomicReferenceFieldUpdater.getAndSet(user,"test");
System.out.println(atomicReferenceFieldUpdater.get(user));
}
static class User{
public User(int age){
this.age = age;
this.ageTmp = age;
}
public int age;
//注意这里如果是想用Atomic原子包下的对应类进行操作的话,要加volatile可见性和public权限
public volatile int ageTmp;
public volatile String name;
}
}