-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep9_Synchronized.java
More file actions
34 lines (28 loc) · 1.48 KB
/
Copy pathStep9_Synchronized.java
File metadata and controls
34 lines (28 loc) · 1.48 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
33
34
public class Step9_Synchronized {
static int count = 0;
// `synchronized`를 사용해 한 번에 하나의 스레드만 해당 메서드를 실행하도록 보호합니다.
// 여러 스레드가 동시에 접근하지 못하도록 제한해야 하는 코드 영역을 임계 영역(critical section)이라고 합니다.
static synchronized void increment() {
count++;
}
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++) {
increment();
}
}, "worker-" + i);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("기대값 = 100000");
System.out.println("실제값 = " + count);
// `synchronized`는 락(lock)을 기반으로 동작하며, 한 번에 하나의 스레드만 임계 영역에 진입하도록 제어합니다.
// 따라서 읽기 → 증가 → 쓰기 과정이 다른 스레드에 의해 중간에 끼어들지 않고 끝까지 수행되어 값이 유실되지 않습니다.
// 또한 락이 해제되기 전에 발생한 변경 사항이 이후 같은 락을 획득한 스레드에 보이도록 보장하므로,
// 원자성과 가시성 문제를 함께 해결할 수 있습니다.
}
}