线程安全的 " i + + "

基于 AtomicInteger 实现原子性操作的i++

  • 使用 AtomicInteger

常用的方法:

//初始化一个 AtomicInteger 初始值为 0
AtomicInteger counter = new AtomicInteger(0);
//counter ++
counter.getAndIncrement();
//counter --
counter.getAndDecrement();
//获取当前值
counter.get();

方法摘要

Modifier and TypeMethod and Description------------
intaccumulateAndGet(int x,IntBinaryOperator accumulatorFunction)自动更新当前值与给定的功能应用到当前和给定值的结果,返回更新后的值。
intaddAndGet(int delta)自动添加给定值和当前值。
booleancompareAndSet(int expect, int update)自动设置的值来指定更新值,如果电流值 ==期望值。
intdecrementAndGet()原子由一个电流值递减。
doubledoubleValue()为扩大基本转换后的 double返回该 AtomicInteger价值。
floatfloatValue()为扩大基本转换后的 float返回该 AtomicInteger价值。
intget()获取当前值。
intgetAndAccumulate(int x,IntBinaryOperator accumulatorFunction)自动更新当前值与给定的功能应用到当前和给定值的结果,返回前一个值。
intgetAndAdd(int delta)自动添加给定值和当前值。
intgetAndDecrement()原子由一个电流值递减。
intgetAndIncrement()原子逐个增加电流值。
intgetAndSet(int newValue)自动设置为给定的值并返回旧值。
intgetAndUpdate(IntUnaryOperator updateFunction)自动更新当前值与结果应用给定的函数,返回前一个值。
intincrementAndGet()原子逐个增加电流值。
intintValue()作为一个 int返回该 AtomicInteger价值。
voidlazySet(int newValue)最终设置为给定的值。
longlongValue()为扩大基本转换后的 long返回该 AtomicInteger价值。
voidset(int newValue)给定值的集合。
StringtoString()返回当前值的字符串表示形式。
intupdateAndGet(IntUnaryOperator updateFunction)自动更新当前值与结果应用给定的函数,返回更新后的值。
booleanweakCompareAndSet(int expect, int update)自动设置的值来指定更新值,如果电流值 ==期望值。

发表留言

人生在世,错别字在所难免,无需纠正。

icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif