'2019/11/08'에 해당되는 글 1건

728x90

쓰레드는 자신의 run() 메소드가 모두 실행되면 자동적으로 종료된다.

하지만, 경우에 따라서는 실행 중인 쓰레드를 즉시 종료할 필요가 있다.

public class StopThread extends Thread {
    public void run() {
        while(true) {
            System.out.println("실행 중");
        }
        System.out.println("자원 정리");
        System.out.println("실행 종료");
    }
}

StopThread는 while(true) 이므로 무한 반복을 하게 된다.


쓰레드를 즉시 종료시키기 위해서 stop() 메소드를 제공하고 있는데, 이는 쓰지 않는다(deprecated 됨).
stop() 메소드는 쓰레드가 사용 중이던 자원들이 불완전한 상태로 남겨지기 때문이다.


안전하게 Thread를 종료시키는 방법은

boolean 변수를 사용하는 방법과 interrupted() 메소드를 이용하는 방법이 있다.



interrupted() 메소드를 이용하는 방법 (권장)

interrupt() 메소드는 일시 정지 상태일 때 정지가 된다.
Thread.sleep(1); // 일시 정지 상태일 경우 interruptedException을 발생시킨다.
실행대기 또는 실행상태에서는 interruptedException이 발생하지 않는다.
일시 정지 상태를 만들지 않고 while문을 빠져나오는 방법 즉 쓰레드를 종료시키는 방법이 있다.
Thread.interrupted() 메소드를 이용하면 된다.

public class StopThread extends Thread {

    public void run() {
        while(true) {
            System.out.println("실행 중");
            if(Thread.interrupted()) {
                break;
            }
        }
        System.out.println("자원 정리");
        System.out.println("실행 종료");
    }
}

public class ThreadStopExample {

    public static void main(String[] args) {
        Thread thread = new StopThread();
        thread.start();
       
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
        thread.interrupt();
    }
}

1초 뒤에 호출되는 thread.interrupt()에 의해 무한 루프는 종료된다.

하지만 더 깔끔하게 처리하는 방법은 StopThread 의 while 문을 아래와 같이 하는 것이다.

public class StopThread extends Thread {

    public void run() {
        while(!Thread.currentThread().isInterrupted()) {
            System.out.println("실행 중");
        }
        System.out.println("자원 정리");
        System.out.println("실행 종료");
    }
}



boolean 변수를 사용하는 방법

public class StopThread extends Thread {
    private boolean flag = false;
   
    StopThread() {
        this.flag = true; // 생성자에 flag 설정
    }
   
    public void Action(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        while(flag) {
            System.out.println("실행 중");
        }
        System.out.println("자원 정리");
        System.out.println("실행 종료");
    }
}

public class ThreadStopExample {

    public static void main(String[] args) {
        Thread thread = new StopThread();
        thread.start();
       
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
        ((StopThread) thread).Action(false);
    }
}


블로그 이미지

Link2Me

,