AtomicInteger原子变量和例题
目录
- AtomicInteger源代码
- 加1操作
- 解决ABA问题的AtomicStampedReference
- 按顺序打印方法
AtomicInteger源代码
// java.util.concurrent.atomic.AtomicIntegerpublic class AtomicInteger extends Number implements java.io.Serializable {private static final long serialVersionUID = 6214790243416807050L;// setup to use Unsafe.compareAndSwapInt for updatesprivate static final Unsafe unsafe = Unsafe.getUnsafe();private static final long valueOffset;static {try {valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));} catch (Exception ex) { throw new Error(ex); }}private volatile int value;/*** Creates a new AtomicInteger with the given initial value.** @param initialValue the initial value*/public AtomicInteger(int initialValue) {value = initialValue;}/*** Creates a new AtomicInteger with initial value {@code 0}.*/public AtomicInteger() {}
加1操作
/*** Atomically increments by one the current value.** @return the previous value*/
public final int getAndIncrement() {return unsafe.getAndAddInt(this, valueOffset, 1);
}
/*** Atomically increments by one the current value.** @return the updated value*/public final int incrementAndGet() {return unsafe.getAndAddInt(this, valueOffset, 1) + 1;}
解决ABA问题的AtomicStampedReference
例子代码
import java.util.concurrent.atomic.AtomicStampedReference;public class AtomicStampedReferenceExample {public static void main(String[] args) {// 初始化AtomicStampedReference,初始值为0和版本号1AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<>(0, 0);// 获取当前值和版本号Integer currentValue = atomicStampedRef.getReference();int[] stampHolder = new int[1];int currentStamp = atomicStampedRef.getStamp(stampHolder);System.out.println("Initial value: " + currentValue + ", Stamp: " + currentStamp);// 尝试更新值和版本号int newStamp = currentStamp + 1;boolean updated = atomicStampedRef.compareAndSet(currentValue, 1, currentStamp, newStamp);if (updated) {System.out.println("Value updated successfully.");} else {System.out.println("Update failed due to wrong stamp or value.");}// 获取更新后的值和版本号currentValue = atomicStampedRef.getReference();currentStamp = atomicStampedRef.getStamp();System.out.println("Updated value: " + currentValue + ", Updated Stamp: " + currentStamp);}
}
按顺序打印方法
leetcode: https://leetcode.cn/problems/print-in-order/
class Foo {AtomicInteger atomicInteger1 = new AtomicInteger(0);AtomicInteger atomicInteger2 = new AtomicInteger(0);public Foo() {}public void first(Runnable printFirst) throws InterruptedException {// printFirst.run() outputs "first". Do not change or remove this line.printFirst.run();atomicInteger1.incrementAndGet();}public void second(Runnable printSecond) throws InterruptedException {while(atomicInteger1.get() != 1){}// printSecond.run() outputs "second". Do not change or remove this line.printSecond.run();atomicInteger2.incrementAndGet();}public void third(Runnable printThird) throws InterruptedException {while(atomicInteger2.get() != 1){}// printThird.run() outputs "third". Do not change or remove this line.printThird.run();}
}