import java.util.concurrent.atomic.AtomicLong; public class Example { public static void main(String[] args) { AtomicLong counter = new AtomicLong(0); long result = counter.addAndGet(5); System.out.println("Result: " + result); // Output: Result: 5 } }
import java.util.concurrent.atomic.AtomicLong; public class Example { public static void main(String[] args) { AtomicLong counter = new AtomicLong(0); Runnable task = () -> { for (int i = 0; i < 10; i++) { long result = counter.addAndGet(1); System.out.println("Result: " + result); } }; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); } }In this example, we create an AtomicLong variable called counter and initialize it with a value of 0. We then create a Runnable task that uses the addAndGet() method to update the counter variable by adding 1 to its current value 10 times. We create two threads t1 and t2 and start them. Because AtomicLong is thread-safe, we can safely update the counter variable from multiple threads without causing any race conditions or inconsistencies. The output of this program will show that both threads are updating the counter variable concurrently, and the final value of the counter variable will be 20. Package library: java.util.concurrent.atomic