Java에서 실행 중인 스레드를 중지하려면 Thread 클래스의 stop() 메서드를 호출하면 됩니다. 이 메서드는 실행 중인 스레드의 동작을 즉시 멈추고, 해당 스레드를 대기 스레드 풀에서 제거한 뒤 가비지 컬렉션 대상으로 만듭니다. 또한 스레드는 run() 메서드의 끝에 도달하면 별도의 호출 없이도 자동으로 종료(Dead) 상태로 전환됩니다.
다만 stop() 메서드는 스레드 안전성(thread-safety) 문제로 인해 Java에서 공식적으로 deprecated(사용 중단 권고) 상태입니다. 스레드가 작업을 처리하던 중간에 강제로 종료되면 공유 자원이 일관성 없는 상태로 남을 수 있기 때문입니다. 따라서 실무에서는 아래 예제처럼 volatile boolean 플래그를 활용해 스레드가 스스로 종료되도록 구현하는 것이 권장됩니다.
문법(Syntax)
@Deprecated public final void stop()
예제 코드
import static java.lang.Thread.currentThread;
public class ThreadStopTest {
public static void main(String args[]) throws InterruptedException {
UserThread userThread = new UserThread();
Thread thread = new Thread(userThread, "T1");
thread.start();
System.out.println(currentThread().getName() + " is stopping user thread");
userThread.stop();
Thread.sleep(2000);
System.out.println(currentThread().getName() + " is finished now");
}
}
class UserThread implements Runnable {
private volatile boolean exit = false;
public void run() {
while(!exit) {
System.out.println("The user thread is running");
}
System.out.println("The user thread is now stopped");
}
public void stop() {
exit = true;
}
}코드 설명
UserThread 클래스 내부에는 volatile 키워드가 붙은 exit 플래그가 선언되어 있습니다. volatile을 사용하면 한 스레드에서 변경한 값이 다른 스레드에 즉시 반영되므로, 메인 스레드에서 stop()을 호출해 exit 값을 true로 바꾸면 사용자 스레드의 while 루프 조건이 false가 되어 루프를 빠져나오게 됩니다.
실행 결과
main is stopping user thread The user thread is running The user thread is now stopped main is finished now
정리
스레드를 중단할 때는 강제 종료 방식인 stop()보다는, 위 예제와 같이 volatile 플래그나 interrupt() 메서드를 활용해 스레드가 안전하게 작업을 마치고 종료되도록 설계하는 것이 좋습니다. 이러한 협력적 종료(cooperative termination) 방식은 데이터 무결성을 지키면서 예측 가능한 멀티스레드 프로그램을 만드는 핵심 원칙입니다.