代码实现:
package com.huang.atomic;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
class User{
private volatile String username;
private volatile Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
public class AtomicRerenceDemo {
static AtomicReference<User> ref = new AtomicReference<>();
public static void main(String[] args) {
/**
* 带有时间戳的原子引用可以解决ABA问题
*
*/
AtomicStampedReference<User> atomicSR = new AtomicStampedReference<>(user1,0);
new Thread(()->{
int stamp = atomicSR.getStamp();
try {
TimeUnit.SECONDS.sleep(3L);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean result = atomicSR.compareAndSet(user1, new User("艾希", 30), stamp, stamp + 1);
System.out.println(Thread.currentThread().getName() + "\t" + stamp+"\t" + atomicSR.getReference());
},"t1线程").start();
new Thread(()->{
int stamp = atomicSR.getStamp();
User user3 = new User("泰达米尔" , 29);
atomicSR.compareAndSet(user1,user3,stamp,stamp + 1);
atomicSR.compareAndSet(user3,user1,atomicSR.getStamp(), atomicSR.getStamp()+1);
System.out.println(Thread.currentThread().getName()+"\t" + atomicSR.getStamp() + "\t" + atomicSR.getReference());
},"t2线程").start();
}
}