-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep10_AtomicCounter.java
More file actions
32 lines (26 loc) · 1.43 KB
/
Copy pathStep10_AtomicCounter.java
File metadata and controls
32 lines (26 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.concurrent.atomic.AtomicInteger;
public class Step10_AtomicCounter {
// `AtomicInteger`는 명시적인 락 없이 원자적 연산을 제공하는 클래스입니다.
static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 10_000; j++) {
// `incrementAndGet()`은 읽기 → 증가 → 쓰기 과정을 하나의 원자적 연산으로 처리합니다.
count.incrementAndGet();
}
}, "worker-" + i);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("기대값 = 100000");
System.out.println("실제값 = " + count.get());
// `AtomicInteger`는 CAS(Compare-And-Swap) 연산을 사용합니다.
// 값을 변경하기 전에 기대값과 현재 값을 비교하고, 두 값이 일치할 때만 값을 갱신합니다.
// 값이 다르면 다른 스레드가 먼저 값을 변경한 것으로 판단하고, 성공할 때까지 재시도합니다.
// 락을 사용하지 않기 때문에 경합이 적은 환경에서는 `synchronized`보다 더 효율적으로 동작할 수 있습니다.
}
}