꿀팁

java.util.concurrent.atomic 패키지 안의 AtomicInteger, AtomicLong 과 같은 클래스들을 활용해보자

Synchronized 키워드의 기능

Thread.stop 은 사용하지 말라

망한 멀티쓰레드

락으로 보호되지 않아서, background 스레드가 수정 이전의 false 결과만을 보기에, 무한루프가 걸려서 i++ 가 무한히 증가한다. 원인: hoisting 최적화 기법 때문에 liveness failure 상태가 되어서

public class StopThread {
    private static boolean stopRequested = false;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(()->{
            int i = 0;
            while(!stopRequested){
                i++;
            }
        });
        backgroundThread.start();

        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}

동기화된 멀티쓰레드

synchronized 를 통해, 락의 보호하에 수행된 모든 수정의 최종 결과를 볼 수 있다. 따라서 1초 후에 루프를 탈출한다.

public class StopThread {
    private static boolean stopRequested;

    private static synchronized void requestStop(){
        stopRequested = true;
    }

    private static synchronized boolean stopRequested(){
        return stopRequested;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(()->{
            int i = 0;
            while(!stopRequested()){
                i++;
            }
        });
        backgroundThread.start();

        TimeUnit.SECONDS.sleep(1);
        requestStop();
    }
}