Atomic Variables
In concurrent programming, atomic variables are special types of variables that ensure atomicity of operations, meaning they provide a way to perform operations on the variable as if they are executed atomically, without interference from other threads.
One common use case of atomic variables is for implementing thread-safe counters. The java.util.concurrent.atomic.AtomicInteger class provides a way to create an integer variable that can be safely accessed and modified by multiple threads.
Here's an example that demonstrates the usage of AtomicInteger to implement a thread-safe counter:
TEXT/X-JAVA
1import java.util.concurrent.atomic.AtomicInteger;
2
3public class Main {
4 public static void main(String[] args) {
5 AtomicInteger counter = new AtomicInteger(0);
6
7 Thread t1 = new Thread(() -> {
8 for (int i = 0; i < 1000; i++) {
9 counter.incrementAndGet();
10 }
11 });
12
13 Thread t2 = new Thread(() -> {
14 for (int i = 0; i < 1000; i++) {
15 counter.incrementAndGet();
16 }
17 });
18
19 t1.start();
20 t2.start();
21
22 try {
23 t1.join();
24 t2.join();
25 } catch (InterruptedException e) {
26 e.printStackTrace();
27 }
28
29 System.out.println("Counter value: " + counter.get());
30 }
31}xxxxxxxxxx31
}import java.util.concurrent.atomic.AtomicInteger;public class Main { public static void main(String[] args) { AtomicInteger counter = new AtomicInteger(0); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.incrementAndGet(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.incrementAndGet(); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Counter value: " + counter.get());OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment



