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:
- Instantiate an AtomicInteger object, with the option to pass an initial value as a parameter: AtomicInteger atomicInteger = new AtomicInteger(0);
- Commonly used methods for performing atomic operations on an integer variable using the AtomicInteger object include:
- get(): Retrieve the value of the current integer variable.
- Set the value of the integer variable to newValue.
- incrementAndGet(): First increase the value of the integer variable, then return the increased value.
- decrementAndGet(): Decrease the value of an integer variable first, and then return the decreased value.
- getAndIncrement(): Return the value of an integer variable first, then increase the value of the integer variable.
- Return the value of the integer variable first, then decrease the value of the integer variable.
- 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.