温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

AtomicLong的原子操作有哪些

发布时间:2025-05-04 19:50:53 来源:亿速云 阅读:140 作者:小樊 栏目:编程语言

AtomicLong 是 Java 并发包 java.util.concurrent.atomic 中的一个类,它提供了一种基于单个变量的原子操作。以下是 AtomicLong 提供的一些主要原子操作方法:

1. 基本操作

  • get(): 获取当前值。
  • set(long newValue): 设置新值。
  • lazySet(long newValue): 异步设置新值,不保证立即可见性。

2. 原子更新操作

  • compareAndSet(long expect, long update): 如果当前值等于预期值,则以原子方式将值设置为更新值。
  • weakCompareAndSet(long expect, long update): 类似于 compareAndSet,但使用了更弱的内存语义。
  • getAndIncrement(): 原子地将当前值加一,并返回旧值。
  • getAndDecrement(): 原子地将当前值减一,并返回旧值。
  • getAndAdd(long delta): 原子地将当前值加上一个增量,并返回旧值。
  • incrementAndGet(): 原子地将当前值加一,并返回新值。
  • decrementAndGet(): 原子地将当前值减一,并返回新值。
  • addAndGet(long delta): 原子地将当前值加上一个增量,并返回新值。

3. 辅助方法

  • getAndUpdate(LongUnaryOperator updateFunction): 使用提供的函数原子地更新当前值,并返回更新前的值。
  • updateAndGet(LongUnaryOperator updateFunction): 使用提供的函数原子地更新当前值,并返回更新后的值。
  • accumulateAndGet(long x, LongBinaryOperator accumulatorFunction): 使用提供的二元操作符原子地将当前值与给定值进行累积运算,并返回结果。
  • getAndAccumulate(long x, LongBinaryOperator accumulatorFunction): 使用提供的二元操作符原子地将当前值与给定值进行累积运算,并返回更新前的值。

4. 其他方法

  • toString(): 返回当前值的字符串表示。
  • hashCode(): 返回对象的哈希码。
  • equals(Object obj): 判断两个对象是否相等。

示例代码

import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongExample {
    public static void main(String[] args) {
        AtomicLong atomicLong = new AtomicLong(0);

        // 原子地增加值
        long newValue = atomicLong.incrementAndGet();
        System.out.println("Incremented value: " + newValue); // 输出: Incremented value: 1

        // 原子地减少值
        newValue = atomicLong.decrementAndGet();
        System.out.println("Decremented value: " + newValue); // 输出: Decremented value: 0

        // 使用 compareAndSet
        boolean updated = atomicLong.compareAndSet(0, 10);
        System.out.println("Updated: " + updated); // 输出: Updated: true
        System.out.println("Current value: " + atomicLong.get()); // 输出: Current value: 10
    }
}

这些方法确保了在多线程环境下对 AtomicLong 实例的操作是线程安全的,无需额外的同步机制。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI