AtomicStampedReference

AtomicStampedReference

private static class Pair<T> {
    final T reference;
    final int stamp;
    private Pair(T reference, int stamp) {
        this.reference = reference;
        this.stamp = stamp;
    }
    static <T> Pair<T> of(T reference, int stamp) {
        return new Pair<T>(reference, stamp);
    }
}
/**
 * Atomically sets the value of both the reference and stamp
 * to the given update values if the
 * current reference is {@code ==} to the expected reference
 * and the current stamp is equal to the expected stamp.
 *
 * <p><a href="package-summary.html#weakCompareAndSet">May fail
 * spuriously and does not provide ordering guarantees</a>, so is
 * only rarely an appropriate alternative to {@code compareAndSet}.
 *
 * @param expectedReference the expected value of the reference
 * @param newReference the new value for the reference
 * @param expectedStamp the expected value of the stamp
 * @param newStamp the new value for the stamp
 * @return {@code true} if successful
 */
public boolean weakCompareAndSet(V   expectedReference,
                                 V   newReference,
                                 int expectedStamp,
                                 int newStamp) {
    return compareAndSet(expectedReference, newReference,
                         expectedStamp, newStamp);
}
final static AtomicStampedReference<Integer> asri = new AtomicStampedReference<>(new Integer(0), 0);
public static void main(String[] args) throws InterruptedException {
    Thread th1 = new Thread(() -> {
        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println(Thread.interrupted());
            }
            Integer currReference = asri.getReference();
            int currStamp = asri.getStamp();
            asri.compareAndSet(currReference, new Integer(currStamp + 1), currStamp, currStamp + 1);
        }
    });
    Thread th2 = new Thread(() -> {
        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                System.out.println(Thread.interrupted());
            }
            Integer currReference = asri.getReference();
            int currStamp = asri.getStamp();
            asri.compareAndSet(currReference, new Integer(currStamp + 1), currStamp, currStamp + 1);
        }
    });
    th1.start();
    th2.start();
    th1.join();
    th2.join();
    Integer currReference = asri.getReference();
    int currStamp = asri.getStamp();
    System.out.println(currReference + "\t" + currStamp);
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值