Item 66

737 단어 thread

public class StopThread {
    private static boolean stopRequest;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable(){
            public void run(){
                int i = 0;
                while(!stopRequest)
                    i++;
            }
        });
        thread.start();
        Thread.sleep(1000);
        stopRequest = true;
    }
}

synchronized의 역할은 라인의 상호 배척을 제어하는 방법이나 Block뿐만 아니라, 이전 라인이 이 대상에 대한 수정을 확보할 수 있다. 예를 들어, 일반적으로 보면 1초 정도가 지나면 멈춰야 하지만, 실제로는 멈추지 않는다. 왜냐하면 메인 라인이 stopRequest 변수에 대한 수정은다른 라인에서는 볼 수 없습니다.

좋은 웹페이지 즐겨찾기