AtomicInteger count = new AtomicInteger(0); int delta = 5; int newCount = count.addAndGet(delta); System.out.println("New count: " + newCount); // output: New count: 5
AtomicInteger balance = new AtomicInteger(100); int deposit = 20; int newBalance = balance.addAndGet(deposit); System.out.println("New balance: " + newBalance); // output: New balance: 120In this example, we create a new AtomicInteger object with an initial value of 100. We then add the value 20 to the AtomicInteger using the addAndGet() method, which atomically updates the value to 120 and returns the new value. The output is then printed to the console. The java.util.concurrent.atomic package is included in the Java standard library.