-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStep11_Volatile.java
More file actions
32 lines (26 loc) · 1.71 KB
/
Copy pathStep11_Volatile.java
File metadata and controls
32 lines (26 loc) · 1.71 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 Step11_Volatile {
// `volatile`을 제거하면 `worker` 스레드가 `running` 값의 변경을 감지하지 못해
// 반복문이 계속 실행되는 상황이 발생할 수 있습니다.
// 각 스레드는 성능 최적화를 위해 변수 값을 CPU 캐시에 저장할 수 있는데,
// `volatile`은 해당 변수의 읽기와 쓰기를 메인 메모리를 기준으로 수행하도록 강제하여
// 한 스레드의 변경 사항이 다른 스레드에 즉시 보이도록 가시성을 보장합니다.
static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long counted = 0;
while (running) { // `running`이 `false`로 변경되면 반복문을 종료합니다.
counted++;
}
System.out.println("[worker] 반복을 종료했습니다. 반복 횟수 = " + counted);
}, "worker");
worker.start();
Thread.sleep(100); // `worker` 스레드가 반복문을 시작할 수 있도록 잠시 대기합니다.
running = false; // `main` 스레드에서 종료 신호를 전달합니다.
System.out.println("[main] 종료 신호를 보냈습니다.");
worker.join();
System.out.println("[main] worker 스레드가 정상적으로 종료되었습니다.");
// `volatile`은 가시성만 보장하고 원자성은 보장하지 않습니다.
// 따라서 `count++`처럼 읽기 → 증가 → 쓰기로 나뉘는 복합 연산에는 적합하지 않습니다.
// 이런 경우에는 `synchronized` 또는 `AtomicInteger`를 사용해야 합니다.
}
}