import java.util.concurrent.atomic.AtomicInteger; public class AtomicExample { public static void main(String[] args) { AtomicInteger counter = new AtomicInteger(0); int previousCount = counter.getAndIncrement(); System.out.println("Previous count: " + previousCount); System.out.println("Current count: " + counter.get()); } }
Previous count: 0 Current count: 1
import java.util.concurrent.atomic.AtomicInteger; public class AtomicExample { public static void main(String[] args) { AtomicInteger counter = new AtomicInteger(0); Runnable r = new Runnable() { public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread " + Thread.currentThread().getName() + ": " + counter.getAndIncrement()); } } }; Thread t1 = new Thread(r, "Thread 1"); Thread t2 = new Thread(r, "Thread 2"); t1.start(); t2.start(); } }
Thread 1: 0 Thread 1: 1 Thread 1: 2 Thread 1: 3 Thread 1: 4 Thread 1: 5 Thread 1: 6 Thread 1: 7 Thread 1: 8 Thread 1: 9 Thread 2: 10 Thread 2: 11 Thread 2: 12 Thread 2: 13 Thread 2: 14 Thread 2: 15 Thread 2: 16 Thread 2: 17 Thread 2: 18 Thread 2: 19In this example, we create an AtomicInteger variable named "counter" and initialize it to 0. We then create two threads that call the same Runnable instance which increments "counter" using the getAndIncrement() method. We then start both threads and observe that the output shows the value of "counter" being incremented atomically even though multiple threads are accessing it simultaneously. The java.util.concurrent.atomic.AtomicInteger class is part of the java.util.concurrent.atomic package.