|
| 1 | +package com.prd.concurrent; |
| 2 | + |
| 3 | +import java.util.Objects; |
| 4 | +import java.util.concurrent.atomic.AtomicReference; |
| 5 | + |
| 6 | +/** |
| 7 | + * AtomicReference测试 |
| 8 | + */ |
| 9 | +public class AtomicReferenceTest { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + |
| 13 | +// normalString(); |
| 14 | + |
| 15 | + beanTest(); |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * 常规使用测试 |
| 20 | + */ |
| 21 | + private static void normalString() { |
| 22 | + String a = new String("a"); |
| 23 | + String b = new String("b"); |
| 24 | + String c = new String("a"); |
| 25 | + AtomicReference<String> reference = new AtomicReference<>(a); |
| 26 | + System.out.println("初始值为:"+reference.get()); |
| 27 | + // 输出为fasle,说明这里使用的引用地址比较,而非对象的equals |
| 28 | + System.out.println("使用c和b是否更新成功:"+reference.compareAndSet(c,b)); |
| 29 | + System.out.println("使用a和b是否更新成功:"+reference.compareAndSet(a,b)); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * 测试equals相等的变量,是否影响cas |
| 34 | + * 结果: |
| 35 | + 初始值为:a1 |
| 36 | + a1和c1是否相等:true |
| 37 | + 使用c1和b1是否更新成功:false |
| 38 | + 使用a1和b1是否更新成功:true |
| 39 | + 分析: |
| 40 | + 这里的cas使用的是内存中的偏移量做的判断,与equlas无关 |
| 41 | + */ |
| 42 | + private static void beanTest() { |
| 43 | + Student a1 = new AtomicReferenceTest().new Student("a1"); |
| 44 | + Student b1 = new AtomicReferenceTest().new Student("b1"); |
| 45 | + Student c1 = new AtomicReferenceTest().new Student("a1"); |
| 46 | + |
| 47 | + AtomicReference<Student> reference1 = new AtomicReference<>(a1); |
| 48 | + System.out.println("初始值为:"+reference1.get().name); |
| 49 | + // 输出为fasle,说明这里使用的引用地址比较,而非对象的equals |
| 50 | + System.out.println("a1和c1是否相等:"+c1.equals(a1)); |
| 51 | + System.out.println("使用c1和b1是否更新成功:"+reference1.compareAndSet(c1,b1)); |
| 52 | + System.out.println("使用a1和b1是否更新成功:"+reference1.compareAndSet(a1,b1)); |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + class Student { |
| 57 | + String name; |
| 58 | + |
| 59 | + public Student(String name) { |
| 60 | + this.name = name; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public boolean equals(Object o) { |
| 65 | + if (this == o) return true; |
| 66 | + if (!(o instanceof Student)) return false; |
| 67 | + Student student = (Student) o; |
| 68 | + return Objects.equals(name, student.name); |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public int hashCode() { |
| 73 | + return Objects.hash(name); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments