AtomicInteger In Java
【摘要】
AtomicInteger
What can AtomicInteger do for you?Set() methodcompareAndSet() methodOther methods to add a value to the AtomicIntegerSubtracting from the AtomicInteger Value
What c...
What can AtomicInteger do for you?
The AtomicInteger class provides you with a int variable which can be read and written actomically.You can create an AtomicInteger with the initial value 0 like this:
AtomicInteger atomicInteger = new AtomicInteger();
If you want to create an AtomicInteger with an initial value,you can do so like this:
AtomicInteger atomicInteger = new AtomicInteger(123);
Set() method
You can set the value of an AtomicInteger instance via the set() method:
atomicInteger.set(235);
compareAndSet() method
The AtomicIngeter class also has an atomic compareAndSet() method.For example:
AtomicInteger atomicInteger = new AtomicInteger(123);
int expectedValue = 123;
int newValue = 555;
atomicInteger.compareAndSet(expectedValue,newValue);
This example first creates an AtomicInteger instance with an initial value of 123.Then it compares the value of the atomicInteger to expectedValue and if they are equal ,the new value of the atomicInteger becomes 555.
Other methods to add a value to the AtomicInteger
- addAndSet():adds a number to the AtomicInteger and returns its value after the addition.
- getAndAdd():adds a number to the AtomicInteger but returns the value the AtomicInteger had before the value was added.
- getAndIncrement(): adds 1 to the value of the AtomicInteger,inside the method,it returns getAndAddInt(this,VALUE,1)
- incrementAndGet():adds 1 to the value of the AtomicInteger,inside the method,it returns getAndAddInt(this,VALUE,1)+1
Subtracting from the AtomicInteger Value
The AtomicInteger class also contains a few methods for subtracting values from the AtomicInteger value atomically.
- decrementAndGet():It actually returns "getAndAddInt(this,VALUE,-1) -1"
- getAndDecrement():It actually returns "getAndAddInt(this,VALUE,-1)"
Most of the developers know the benefits of threads(responsiveness,exploiting,multicores,etc),most of them also know the risks of threads(data inconsistency,deadlock,context switch overhead,etc).
Thread synchronization is needed when multiple threads access some changeable data and one of them might change it.
Synchronization provided in java enables us to enforce two things:atomicity and visibility.
When you want to change an Integer variable between threads,beside using synchronized key word,you can use AtomicIngeter class to achieve it.
文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_40763897/article/details/113795133
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)