본문 바로가기
Development/Java & Android

Killing Thread

by nickeys 2010. 8. 27.
# Is it dangerous to directly killing thead?
=> Thread를 그냥 죽이게 되면 어떤 처리 도중에 중단 될 수 있으므로 위험하다.
따라서, 자연스럽게 한 과정을 끝내고 다음 transaction을 수행할 때 종료해 주는 것이 자연스럽다.

# Then, how to do it like above?
=> Thread를 확장하거나(extends) Runnable 인터페이스를 구현(implements)한 클래스는 interrupt라는 메소드를 가진다.
Thread는 보통 while루프 안에서 지속적으로 실행 하도록 구현 하는데, while의 조건으로 flag로 boolean형 변수를 두는게
일반적이므로, 그 flag를 intterupt메소드 안에서 처리 되도록 overriding 하면 된다(물론 intterupt라는 메소드 내에서 굳이 처리 할
필요는 없으나, 제공하는 메소드를 overriding하는 것이 의미상으로도 보기에 낫다).

# Example
@Override
    public void run() {
        while(this.flag) {
            // do sth
        }
    }
If the thread is existing,

@Override
    public void intterupt() {
        this.flag = false;
    }
the flag set to false when wanting to kill the thread.