AtomicInteger counter = new AtomicInteger(0); int previousValue = counter.getAndAdd(2); System.out.println("Previous value: " + previousValue); System.out.println("Current value: " + counter.get());
AtomicInteger counter = new AtomicInteger(10); Runnable runnable = () -> { int previousValue = counter.getAndAdd(-1); System.out.println("Previous value: " + previousValue); System.out.println("Current value: " + counter.get()); }; Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start();In this example, we create an AtomicInteger with an initial value of 10. We define a Runnable that decrements the AtomicInteger by 1 using getAndAdd(-1), and prints out the previous and current values. We then create two threads that run the same Runnable, simulating multiple threads modifying the counter. We print out the previous and current values to verify that the method worked correctly in a concurrent environment. Both examples use the java.util.concurrent.atomic package.