AtomicInteger

AtomicInteger 是一个在 java.util.concurrent.atomic 包中的类,它提供了一种原子操作来更新 int 类型的值。这意味着,使用 AtomicInteger 的操作可以在不使用锁的情况下在多线程环境中安全地执行。

使用 AtomicInteger 的一个常见场景是使用它来维护一个计数器。例如,可以使用 AtomicInteger 来统计一个应用程序中的活动线程数,或者在线程安全地统计计数器时使用它。

下面是一个使用 AtomicInteger 的示例代码:

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter {
    private final AtomicInteger counter = new AtomicInteger();

    public void increment() {
        counter.incrementAndGet();
    }

    public int getValue() {
        return counter.get();
    }
}

在上面的代码中,我们创建了一个 AtomicCounter 类,其中包含一个内部的 AtomicInteger 对象。我们提供了一个 increment 方法来增加计数器的值,并使用 AtomicInteger 类的 incrementAndGet 方法来原子地增加计数器的值。我们还提供了一个 getValue 方法来返回计数器的当前值。

总之,AtomicInteger 是一个非常有用的类,可以在多线程环境中安全地维护一个 int 类型的变量。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值