728x90
volatile 은 변수의 가시성을 보장하고 동시성 문제를 해결할 수 있다.
volatile
- 변수의 값을 스레드 간 최신 상태로 유지한다.
- 캐시 대신 메인 메모리에서 읽고 쓴다.
- 간단한 플래그나 상태 변수에 유용하다.
사용하는 이유
- 스레드가 변수 값을 캐시에 저장하면 다른 스레드에서 변경된 값이 보이지 않는다.
- 메모리 가시성을 보장한다.
- 복잡한 동기화는 synchronized 필요
public class VolatileExample {
private boolean running = true;
public void stop() {
running = false;
}
public static void main(String[] args) throws InterruptedException {
VolatileExample example = new VolatileExample();
Thread worker = new Thread(() -> {
while (example.running) {
System.out.println("Working...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("Stopped!");
});
worker.start();
Thread.sleep(500);
example.stop();
}
}
//출력값
Working...
Working...
Working...
Working...
Working...
Stopped!
728x90
'Language > JAVA' 카테고리의 다른 글
[자바 멀티스레딩] 자바 동시성 고급: CountDownLatch 사용법 (0) | 2025.03.31 |
---|---|
[자바 멀티스레딩] 자바 동시성 고급: ReentrantLock 사용법 (0) | 2025.03.30 |
[자바 멀티스레딩] 동기화: synchronized 과 AtomicInteger 사용법 (0) | 2025.03.28 |
[자바 멀티스레딩] 스레드 풀: ExecutorService 사용법 (0) | 2025.03.27 |
[자바 멀티스레딩] 스레드 기초: Thread 클래스와 Runnable 인터페이스 (0) | 2025.03.26 |
댓글