1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| public class ABADemo { static AtomicInteger atomicInteger = new AtomicInteger(100); static AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<>(100, 1); public static void main(String[] args) { new Thread(() -> { int stamp = stampedReference.getStamp(); System.out.println(Thread.currentThread().getName() + "\t" + "首次版本号:" + stamp); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } stampedReference.compareAndSet(100, 101, stampedReference.getStamp(), stampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t" + "2次流水号:" + stampedReference.getStamp()); stampedReference.compareAndSet(101, 100, stampedReference.getStamp(), stampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t" + "3次流水号:" + stampedReference.getStamp()); }, "t3").start(); new Thread(() -> { int stamp = stampedReference.getStamp(); System.out.println(Thread.currentThread().getName() + "\t" + "首次版本号:" + stamp); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } boolean b = stampedReference.compareAndSet(100, 2022, stamp, stamp + 1); System.out.println(b + "\t" + stampedReference.getReference() + "\t" + stampedReference.getStamp()); }, "t4").start(); } private static void abaHappen() { new Thread(() -> { atomicInteger.compareAndSet(100, 101); try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } atomicInteger.compareAndSet(101, 100); }, "t1").start(); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicInteger.compareAndSet(100, 2022) + "\t" + atomicInteger.get()); }, "t2").start(); } }
|