The use of Atomicinteger in Java!!!

Source: Internet
Author: User

Today in the volley to see the source of the time, see the use of Atomicinteger this class, once useless, today looked at the API to learn a bit:

First introduce the use of this class, this class is mainly used to replace the Java self-increment and self-reduction operations, that is, i++ and ++i, and so on, why to use this class, mainly because the i++ and i--and other operations are thread insecure, so you need this class to replace, and then not much to say, Directly on the code, can not understand the ability to participate in the Help document:

public class Test {public static void main (string[] args) {Atomicinteger integer = new Atomicinteger (); Integer.set (1); int i = Integer.get (); Obtained value System.out.println (i); i = Integer.incrementandget (); First +1, then the return value, equivalent to ++ISYSTEM.OUT.PRINTLN (i); i = Integer.getandincrement ();//return value first, then +1, equivalent to I++SYSTEM.OUT.PRINTLN (i); i = Integer.get (); System.out.println (i); i = Integer.decrementandget ();//First-1, then the return value, equivalent to--ISYSTEM.OUT.PRINTLN (i); i = Integer.getanddecrement ();//return value first, then at-1, equivalent to I--SYSTEM.OUT.PRINTLN (i); i = Integer.get (); System.out.println (i);//1 i = integer.addandget (1);//+n First, then in return value, System.out.println (i); i = Integer.getandadd (1);// First return, then +nsystem.out.println (i); i = Integer.get (); System.out.println (i);}}
The result of the output is:

1223221223


The use of Atomicinteger in Java!!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.