import java.util.concurrent.atomic.AtomicLong; public class AtomicLongExample { static AtomicLong counter = new AtomicLong(0); public static void main(String[] args) { System.out.println("Counter before incrementing: " + counter.get()); // prints "Counter before incrementing: 0" long result = counter.getAndIncrement(); System.out.println("Value returned from getAndIncrement(): " + result); // prints "Value returned from getAndIncrement(): 0" System.out.println("Counter after incrementing: " + counter.get()); // prints "Counter after incrementing: 1" } }
import java.util.concurrent.atomic.AtomicLong; public class AtomicLongExample { static AtomicLong counter = new AtomicLong(0); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println(counter.getAndIncrement()); } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println(counter.getAndIncrement()); } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println("Final value of Counter: " + counter.get()); } }
0 1 2 3 4 5 6 7 8 9 Final value of Counter: 10As expected, each thread fetches the current value of `counter`, increments it and prints the updated value. The final value of `counter` after both threads have completed their execution is 10.