본문 바로가기
Language/JAVA

[자바 멀티스레딩] 동시성 제어: volatile 사용법

by YoonJong 2025. 3. 28.
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

댓글