Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 한 스레드가 다른 스레드를 인터럽트(interrupt)하는 방법

Java에서는 interrupt() 메서드를 사용하여 실행 중인 스레드를 중단(인터럽트)할 수 있습니다. 이때 InterruptedException 예외가 핵심 역할을 합니다. 대상 스레드가 sleep(), wait(), join()과 같은 블로킹 상태에 있을 때 interrupt()가 호출되면 해당 스레드는 InterruptedException을 받게 되며, 이를 catch 블록에서 처리하여 원하는 방식으로 실행을 종료하거나 제어할 수 있습니다.

아래 예제는 현재 실행 중인 스레드가 인터럽트되면 catch 블록에서 새로운 RuntimeException을 발생시켜 스레드의 실행이 중단되는 과정을 보여줍니다.

예제 코드

public class Demo extends Thread
{
    public void run()
    {
        try
        {
            Thread.sleep(150);
            System.out.println("In the 'run' function inside try block");
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException("The thread has been interrupted");
        }
    }
    public static void main(String args[])
    {
        Demo my_inst = new Demo();
        System.out.println("An instance of the Demo class has been created");
        my_inst.start();
        try
        {
            my_inst.interrupt();
        }
        catch (Exception e)
        {
            System.out.println("The exception has been handled");
        }
    }
}

실행 결과

An instance of the Demo class has been created
Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted
at Demo.run(Demo.java:12)

코드 설명

Demo 클래스 정의: Demo 클래스는 Thread 클래스를 상속받아 작성되었습니다. run() 메서드 내부의 try 블록에서는 Thread.sleep(150)을 호출하여 스레드를 150밀리초 동안 일시 정지시킵니다. 이후 콘솔에 메시지를 출력합니다.

인터럽트 처리: 만약 스레드가 sleep 중일 때 interrupt()가 호출되면 InterruptedException이 발생하고, catch 블록이 이를 감지하여 "스레드가 인터럽트되었다"는 메시지를 담은 RuntimeException을 던집니다. 결과적으로 스레드는 정상적으로 run() 메서드를 끝까지 실행하지 못하고 비정상 종료됩니다.

main 메서드 동작: main 함수에서는 Demo 클래스의 인스턴스를 생성한 뒤 start() 메서드로 스레드를 시작합니다. 이어서 try 블록 안에서 my_inst.interrupt()를 호출하여 해당 스레드를 인터럽트하고, 필요한 경우 catch 블록에서 발생할 수 있는 예외를 추가로 처리할 수 있습니다.

정리

이처럼 Java의 interrupt() 메서드는 스레드 간 협력적 취소(cooperative cancellation)를 구현하는 기본 수단입니다. 단, interrupt() 호출 자체가 스레드를 강제로 종료시키는 것은 아니며, 대상 스레드가 InterruptedException을 적절히 처리하거나 인터럽트 상태(Thread.interrupted())를 확인하는 로직을 가져야만 실질적인 중단이 이루어진다는 점을 기억해야 합니다.