-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep8_RaceCondition.java
More file actions
32 lines (27 loc) · 1.49 KB
/
Copy pathStep8_RaceCondition.java
File metadata and controls
32 lines (27 loc) · 1.49 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
public class Step8_RaceCondition {
// 여러 스레드가 함께 사용하는 공유 변수입니다.
static int count = 0;
public static void main(String[] args) throws InterruptedException {
// 10개의 스레드가 각각 `count`를 10,000번씩 증가시킵니다.
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++) {
count++;
}
}, "worker-" + i);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("기대값 = 100000");
System.out.println("실제값 = " + count);
System.out.println("누락된 증가 연산 = " + (100_000 - count) + "회");
// 기대값은 100,000이지만 실제 결과는 이보다 작게 나올 수 있습니다.
// `count++`는 한 줄로 작성되어 있지만 내부적으로는 읽기 → 증가 → 쓰기의 세 단계로 나뉘어 실행됩니다.
// 두 스레드가 같은 값을 동시에 읽으면 각각 1을 더한 뒤 동일한 값을 다시 쓰게 됩니다.
// 이 과정에서 두 번의 증가 연산이 하나로 합쳐지면서 일부 증가가 누락됩니다.
// 이처럼 여러 스레드가 공유 자원에 동시에 접근하면서 실행 결과가 달라지는 현상을 경쟁 상태(race condition)라고 합니다.
}
}