AtomicInteger atomicInt = new AtomicInteger(10); int value = atomicInt.get(); System.out.println("Value of atomicInt: " + value);
Value of atomicInt: 10
class Counter implements Runnable { private AtomicInteger count; public Counter(AtomicInteger count) { this.count = count; } public void run() { for (int i = 0; i < 100000; i++) { count.getAndIncrement(); } } } public class AtomicCounter { public static void main(String[] args) throws InterruptedException { AtomicInteger count = new AtomicInteger(0); Thread t1 = new Thread(new Counter(count)); Thread t2 = new Thread(new Counter(count)); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final count value: " + count.get()); } }
Final count value: 200000In the above example, two threads increment the atomic integer `count` using the `getAndIncrement()` method. As this method atomically increments the value and returns the previous value, the final value of `count` is double the number of increments made by each thread. The package library for AtomicInteger is `java.util.concurrent.atomic`.