📅  最后修改于: 2023-12-03 15:31:49.873000             🧑  作者: Mango
AtomicInteger get()
方法及示例AtomicInteger
类是 Java 中提供的一个能够实现原子操作的整型类。其中的方法都是线程安全的,可以避免多个线程同时操作同一个值时出现的问题。
其中,get()
方法用于获取当前 AtomicInteger
实例的值。本文将介绍 get()
方法的使用方法,并提供一个示例代码。
public final int get()
方法返回当前 AtomicInteger
实例的值,以整型的形式返回。
下面的代码展示了 AtomicInteger get()
方法的使用示例,该示例提供了一个计数器,每个线程对其进行加一操作,并输出当前的值。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
int currentValue = counter.get();
System.out.println(Thread.currentThread().getName() + " current value: " + currentValue);
int newValue = currentValue + 1;
counter.set(newValue);
System.out.println(Thread.currentThread().getName() + " new value: " + counter.get());
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
int currentValue = counter.get();
System.out.println(Thread.currentThread().getName() + " current value: " + currentValue);
int newValue = currentValue + 1;
counter.set(newValue);
System.out.println(Thread.currentThread().getName() + " new value: " + counter.get());
}
});
t1.start();
t2.start();
}
}
代码的执行结果如下:
Thread-0 current value: 0
Thread-0 new value: 1
Thread-0 current value: 1
Thread-0 new value: 2
Thread-0 current value: 2
Thread-0 new value: 3
Thread-0 current value: 3
Thread-0 new value: 4
Thread-0 current value: 4
Thread-0 new value: 5
Thread-0 current value: 5
Thread-0 new value: 6
Thread-0 current value: 6
Thread-0 new value: 7
Thread-0 current value: 7
Thread-0 new value: 8
Thread-0 current value: 8
Thread-0 new value: 9
Thread-0 current value: 9
Thread-0 new value: 10
Thread-1 current value: 10
Thread-1 new value: 11
Thread-1 current value: 11
Thread-1 new value: 12
Thread-1 current value: 12
Thread-1 new value: 13
Thread-1 current value: 13
Thread-1 new value: 14
Thread-1 current value: 14
Thread-1 new value: 15
Thread-1 current value: 15
Thread-1 new value: 16
Thread-1 current value: 16
Thread-1 new value: 17
Thread-1 current value: 17
Thread-1 new value: 18
Thread-1 current value: 18
Thread-1 new value: 19
从上面的结果可知,两个线程对 AtomicInteger
实例进行的加一操作都是线程安全的,并且能够确保最终结果的正确。因此,get()
方法在多线程环境下常常被使用来获取可变对象的最新值。