How do you use AtomicInteger in Java?

AtomicInteger is a class provided in the java.util.concurrent.atomic package that allows for atomic operations on an integer variable in a multi-threaded environment.

The steps for using the AtomicInteger class are as follows:

  1. Instantiate an AtomicInteger object, with the option to pass an initial value as a parameter: AtomicInteger atomicInteger = new AtomicInteger(0);
  2. Commonly used methods for performing atomic operations on an integer variable using the AtomicInteger object include:
  3. get(): Retrieve the value of the current integer variable.
  4. Set the value of the integer variable to newValue.
  5. incrementAndGet(): First increase the value of the integer variable, then return the increased value.
  6. decrementAndGet(): Decrease the value of an integer variable first, and then return the decreased value.
  7. getAndIncrement(): Return the value of an integer variable first, then increase the value of the integer variable.
  8. Return the value of the integer variable first, then decrease the value of the integer variable.
  9. compareAndSet(int expect, int update): If the current value of the integer variable is equal to the expected value, set the value of the integer variable to the update value and return true; otherwise, return false.

Here is a simple example code:

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        System.out.println("初始值:" + atomicInteger.get());

        atomicInteger.incrementAndGet();
        System.out.println("增加后的值:" + atomicInteger.get());

        atomicInteger.compareAndSet(1, 10);
        System.out.println("比较并设置后的值:" + atomicInteger.get());
    }
}

The output result is:

初始值:0
增加后的值:1
比较并设置后的值:10

It can be seen from the example code that the AtomicInteger class can ensure atomicity of operations on integer variables in a multi-threaded environment, avoiding data race and concurrency issues.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds